I am trying to reorganize someone's code and I seem to have hit a wall.
I have a function int fnc()
in fnc.c
that is called by either main1.c
or main2.c
. An executable is compiled from either main1.c
or main2.c
using a makefile:
main1: main1.o fnc.o
gcc main1.o fnc.o -o main1.x
main2: main2.o fnc.o
gcc main2.o fnc.o -o main2.x
main1.o: main1.c
gcc -c main1.c
main2.o: main2.c
gcc -c main2.c
fnc.o:
gcc -c fnc.c
The only problem is, there are two header files header1.h
and header2.h
to be included in the preamble of fnc.c
depending on whether main1.x or main2.x is compiled:
#include "header1.h"
int fnc(){
// do stuff
}
Is it possible to select which header to be loaded depending on whether one types make main1
or make main2
?
You can use the -D
compiler flag to define a symbol that will be visible to preprocessor. And then to check it with the preprocessor #ifdef
directive. Such as:
Makefile:
main1: main1.o fnc1.o
gcc main1.o fnc1.o -o main1.x
main2: main2.o fnc2.o
gcc main2.o fnc2.o -o main2.x
main1.o: main1.c
gcc -c main1.c
main2.o: main2.c
gcc -c main2.c
fnc1.o:
gcc -o fnc1.o -c fnc.c -DCONFIG1
fnc2.o:
gcc -o fnc2.o -c fnc.c -DCONFIG2
And your source:
#ifdef CONFIG1
#include "header1.h"
#elif defined(CONFIG2)
#include "header2.h"
#else
#error "blah"
#endif
int fnc(){
// do stuff
}