define macro in pro file

Why need to define macros in Qt project file?

I have a tool source library. The library contains several header files and source files. I used conditional compilation in both the headers and the sources. I use some functions in the lib when developing my main app so I include the header files in the source code of the main app. I could define a macro in the source code of the main app just before the inclusion of the header files so the conditional  compilation for the headers can be done correctly. But how about the compilation of the source code of the tool library? They cannot get the macro definition when being compiled. You may argue that I can add the macro definition to the lib source as well. Moreover, I could define the macro in the header of the lib, then the source of the lib can be compiled correctly because it includes the lib header. However, this is not the correct way to use a lib. The lib source code should not depend on the usage of the lib. It should only contain the usage of macros(the conditional  compilation #if/#ifnded/#else/#endif), not the definition of macros.

So we should not define the macro in the library. We should not define the marcos in the source code of the app too, as described above. The place we define the macro is the .pro file. This way, the macro has global effect, i.e., both the main app and the lib get the macro definition.

How to define macros in qt pro file?

You should add the line “DEFINES+=macrodef” in your pro file. Then, when building the project, the compiler command would be g++ -Dmacrodef …. Of course, you can define macro name and macro value at the same time like

DEFINES+="MYMACRONAME=MYMACROVALE"

Now the compiling command would be g++ -DMYMACRONAME=MYMACROVALE…

Reference:https://stackoverflow.com/questions/30185212/how-to-add-macro-defines-in-qt-pro-file

 

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!
Posted in

Leave a Reply