In my project, I define a macro called ACT_STATE
in a header file config.h
to make different blocks of code be compiled. Macro ACT_STATE
could be ACT_DEVELOP
(value 0) or ACT_DEPLOY
(value 1), I want source files in a folder called User
could be compiled at state ACT_DEPLOY
and leave those source files alone at state ACT_DEVELOP
. I know I can pass macro definition to makefile while calling make
, but by this way I need to define ACT_STATE
twice. Therefore, I think if it is possible to let make
read macro definition from head files, so it could compile different files depending on macro definition in a header file?
Asked
Active
Viewed 399 times
0

Shan-Hung Hsu
- 127
- 2
- 14
-
1There isn't a standard or easy way to have make read a macro value from a header. It would be more usual to have make specify the value so the header doesn't have to, or so the header specifies a default if make does not specify the value. – Jonathan Leffler Feb 07 '21 at 04:37
-
1There is no need to define the macro twice. If you pass it through Make (`make ACT_STATE=ACT_DEPLOY`) then there is no reason to define it in the header. – Beta Feb 07 '21 at 05:36
-
2Remember that C code (in particular some `#include`d file) can be *generated* by a program. The [GNU autoconf](https://www.gnu.org/software/autoconf/) tool could be useful to you – Basile Starynkevitch Feb 07 '21 at 07:39
-
@Beta for a proper config management it is desirable to not hinge upon the very transient and volatile command line which starts the build process. Of course one can always add another layer of scripting, but IMHO this isn't desirable either. – Vroomfondel Feb 08 '21 at 10:48
-
@Vroomfondel: I have seen config management systems that performed, e.g., sweeping backups and builds of the main branch every midnight. But I've never seen a build system that could build something on command in a way that *didn't* hinge on the command line. (I am, of course, not counting GUI-based abominations). If there's a better alternative, I'm keen to learn it. – Beta Feb 08 '21 at 13:53
1 Answers
2
gcc -D name=definition
However, ACT_DEVELOP 0
and ACT_DEPLOY 1
is not the simplest way to make a binary variable. There is no reason why one can't write #define ACT_STATE 7
or #undef ACT_STATE
, leading to complicated range checks. A preferable way is #ifdef
or #if defined(...)
.
gcc -D name
Unless you have a good reason to do this, consider the C
standard assert.h. With C11
, one can do static_assert
that is really useful in some cases. The assert.h
trigger is NDEBUG
, which, when defined, makes assert
arguments compile to (void)0
.
Also see passing additional variables to make
to edit one's Makefile
.

Neil
- 1,767
- 2
- 16
- 22