Home > database >  Make a version file of macros which run at compile time
Make a version file of macros which run at compile time

Time:12-05

I want to ask if I can make a file of macros that basically defined at compile time and use these macros in my c code which compiles specific code if the condition is true. SO what is basically the extension for that file is it a .txt file or a .h file. and how to put this file in CmakeList.txt to make it executable at compile time. for example like this in a specific file?

#define melodic 1
#define noetic 2

CodePudding user response:

A C macro is a shortcut for writing code, what happens when you compile your project is that this code:

#define SOMETHING 32
int i = SOMETHING

Is changed to before it is compiled:

int i = 32

So a macro just substitutes text wherever you place it. There is also another use of macros that maybe is what you are looking for. You can use the preprocessing directive #ifdef MACRO to compile some code conditionally. For example, let's say that you have a function that is only there for debugging, but you don't want that code to make it to release. You could define it like:

void hello() {
#ifdef DEBUG
    print("debug");
#endif
}

Then, if that file has a #define DEBUG before the #ifdef macro, the code will be included. Otherwise, the code will be discarded. Note that to use #ifdef the macro body may be empty or not, it just checks if the defined directive was used.

What you might want to accomplish is to have a series of preprocessor macros that you either set or don't in a separate configuration file to change the code produced. They are a very powerful tool, but they must be use with caution since having too many can make code not very readable.

To accomplish that, you need to include the #define MACRO in the same file that you are checking if it is defined, and before you check it. If you are only using that macro in that file, it would be good to place it at the top of it, but if you use it on multiple files you can create a header file (.h) and use #include "name.h", since include copies the contents of the header file there, therefore adding the macro definitions to your file.

The preprocessor directives are dependent on the compiler, so the version and type of compiler you use (gcc, clang...) will have different support for them. However, defined and ifdef are very widely spread and most if not all compilers have them. I recommend reading more about directives, for example here.

Finally, in case you go the route of the .h file, you would add it like any other header file you have in your project to the CmakeList.txt.

  • Related