Tim Tim - 2 months ago 14
C Question

macro in makefile? Conditional h-file inclusion?

Let me explain my situation:
I have a program that contains different kinds of models (let's say 10, but the actual number is quite high). All these models have a name and corresponding file "model1.cu" and "model1.h". All of these files have a function that produces one float number and returns it, which is in all files named the same, with the same arguments (let's say

float returnfunction(float voltage)
). This particular function is needed in the main file.
In the makefile I have put an option such that you compile only the code for the model you will be calculating with as follows:

ifdef MODEL1
SRCS := model1.cu
OBJS := model1.o
endif

ifdef MODEL2
SRCS := model2.cu
OBJS := model2.o
endif

SRCS += main.c


Now I can select the correct model by typing "make MODEL1=1". The problem arises in the main-file. The function
returnfunction(float voltage)
is defined in model1.h, so I should include it. But when I include

#ifdef MODEL1
#include "model1.h"
#endif

#ifdef MODEL2
#include "model2.h"
#endif


in my main.c file, I get the error that the function
returnfunction
is not defined anywhere.
Is there a way to get the correct h-file included in my main-file? Preferably by using that I already compile by using MODEL1 = 1.

Any help is greatly appreciated!

Answer

You can simply add a preprocessor definition to your Makefile, for each model you have. For example, in the case of MODEL1=1:

ifdef MODEL1
SRCS := model1.cu
OBJS := model1.o
CFLAGS += -DMODEL1
endif

Assuming you are using the implicit rules, the modified CFLAGS will be passed to every file that is compiled. If you've used your own rule to compile main.c (and aren't using CFLAGS), then you could create a variable, and pass it in explicitly.

Comments