bits
bits

Reputation: 319

Use gcc preprocessor to define filename for #include

I would like to specify the name of a C include file at compile time as a C flag.

e.g.

#include MY_INCLUDE_FILE
int main(int argc, const char * argv[]) {...}

Would be expaned by the pre-processor to

#include "some_incfile.h"
int main(int argc, const char * argv[]) {...}

Doing something like this

gcc -DMY_INCLUDE_FILE="some_incfile.h" main.c

I have attempted using the stringizing operator # to expand but have only gotten errors such as error: expected "FILENAME" or <FILENAME>

Is this even possible? -D define is not entirely necessary, the important part is that the include filename can be set from the gcc command line

Upvotes: 4

Views: 2276

Answers (3)

alinsoar
alinsoar

Reputation: 15793

You can do it something like that

#  if defined AAA
#define INC "x.h"
#elif defined BBB
#define INC "y.h"
#endif

#include INC

and from command line you do gcc -DAAA.

and of course, you can pass directly gcc -DINC="\"FILE.h\"" if the file is really randomly generated from outside, by makefiles, etc.

Important is INC to be evaluated to a valid file name by the macro expansion procedure (see the Prosser's algorithm).

Upvotes: 1

koalo
koalo

Reputation: 2313

You have to escape the ":

gcc -DMY_INCLUDE_FILE=\"some_incfile.h\" main.c

Upvotes: 6

anonymoose
anonymoose

Reputation: 868

Use the -include option.

gcc -include "somefile.h" main.c

Upvotes: 3

Related Questions