Home > Back-end >  How to execute a single preprocessor directive in a C file
How to execute a single preprocessor directive in a C file

Time:07-12

I have a main.c file containing one or more preprocessor macros defined:

#include <stdio.h>

#define VALUE 12

int main(void) {
    printf("This file is in version %s and contains value %d\n", VERSION, VALUE);
    return 0;
}

I want to export a main2.c file with only the #define VERSION "1.0" applied to the original source file.

What I tried:

  • gcc -DVERSION=\"1.0\" -E will apply ALL the preprocessor directives instead of the single one I want
  • sed 's/VERSION/\"1.0\"/g' will probably replace more than needed, and will need more work if I need more than a single directive
  • cppp is a nice tool but may alter the source file a lot. Only supports simple defines with numerical values

Is there any way to execute only parts of preprocessor directives with gcc ?

CodePudding user response:

EDIT: This is a non maintainable solution - but it works. Don't use this if you expect your project to grow into several versions over time.

My attempt makes use of preprocessor conditional code and string concatenation (the fact that in C you can do "abc" "def"and it will be trated as "abcdef".

#include <stdio.h>

#ifdef V1
#define VERSION "1"
#define VALUE 99
#else
#define VERSION "2"
#define VALUE 66
#endif


int main(void) {
    printf("This file is in version " VERSION " and contains value %d\n", VALUE);
    return 0;
}

which prints

>> ~/playground/so$ gcc -DV1 q1.c 
>> ~/playground/so$ ./a.out 
This file is in version 1 and contains value 99
>> ~/playground/so$ gcc -DV2 q1.c 
>> ~/playground/so$ ./a.out 
This file is in version 2 and contains value 66



CodePudding user response:

Read about autoconf https://www.gnu.org/software/autoconf/

and maybe even about automaker (if you want to generate makefiles) https://www.gnu.org/software/automake/.

  • Related