C语言 是否可以在 makefile 中定义 C 宏?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5302390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to define a C macro in a makefile?
提问by Richard
Is it possible to put the equivalent of #define VAR(in a C program) into a makefile, so that one can control which part of the program should be compiled?
是否可以将#define VAR(在 C 程序中)的等价物放入 makefile 中,以便可以控制应编译程序的哪一部分?
采纳答案by Zimbabao
Accordingly to ccmanpage on linux
相应的cc联机帮助页linux
-D name=definition
The contents of definition are tokenized and processed as if they appeared during translation phase three in a #define directive. In
particular, the definition will be truncated by embedded newline characters.
回答by AntoineL
Edit your Makefileto show
编辑您的Makefile以显示
CFLAGS=-D VAR1-D VAR2=*something*
CFLAGS=-D VAR1-D VAR2=*某事*
If you are using default rules in the Makefile, this should work automatically. If you do not, and are invoking the C compiler explicitely, just make sure you are writing something along the lines of
如果您在 Makefile 中使用默认规则,这应该会自动工作。如果你不这样做,并且明确地调用了 C 编译器,只要确保你正在写一些类似的东西
$(CC) $(CFLAGS) -c -o $@ $<
$(CC) $(CFLAGS) -c -o $@ $<
Even more cute if the fact the CFLAGS=...above can be used on the command line rather than written in the Makefile (read man(1)manual page); this allows for easy reconfiguration of your compilation parameters at last moment, but the parameters won't be kept.
如果上述事实CFLAGS=...可以在命令行上使用而不是写在 Makefile 中(阅读man(1)手册页),那就更可爱了;这允许在最后时刻轻松重新配置编译参数,但不会保留参数。
Best practices include using CPPFLAGSinstead of CFLAGS, and using +=instead of =; however support for these features are not as universal as the above, and depend on your make system.
最佳实践包括使用CPPFLAGS替代CFLAGS和使用+=替代=;然而,对这些功能的支持并不像上述那样普遍,并且取决于您的 make 系统。

