Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

When are #includes necessary, and when are they not?



  • Hello forums, I have two questions about Qt #includes.

    I'm just getting started with Qt, and I noticed that there are certain classes that, in order to use them, they must be explicitly be included into the project in the header file by writing an "#include <xyz>" statement. For example, in order to correctly use the QFile class in your source code, you must first write in mainwindow.h:

    #include <QFile>
    

    However, I have also noticed that there are certain classes that seem to be implicitly included. That is, there are Qt classes that I can use in my source code without writing an include statement in the header file. One such example is the QIODevice class.

    Question 1: Why are certain classes usable without an #include statement?
    Question 2: How do I know which classes require an explicit #include, and which ones don't?

    Thank you!


  • Qt Champions 2017

    @Yuta said in When are #includes necessary, and when are they not?:

    Question 1: Why are certain classes usable without an #include statement?

    They are not. The headers are just included somewhere in the headers you include. This, however, can change at any one time and you're strongly encouraged to explicitly include all the necessary class headers.

    @Yuta said in When are #includes necessary, and when are they not?:

    Question 2: How do I know which classes require an explicit #include, and which ones don't?

    Assume all of them do and act as if all of them do.



  • @kshegunov Understood, thanks for the answer!


  • Lifetime Qt Champion

    Hi,

    One small example to illustrate that: lots of code were using QRegExp while not including it. It was working because it was included by QString and that's a class that is pretty common.

    I'll let you guess the aftermath when the include got removed during a header cleanup. Lot's of Qt modules did not like it.


Log in to reply