从 makefile 定义宏函数

Defining macro function from makefile

假设我的 makefile 中有以下条目:

ifeq ($(MY_DEBUG),yes) 
EXTRACXXFLAGS += -DMY_DEBUG=2
endif

我用 make foo MY_DEBUG=yes 调用它,现在我基本上有

#define MY_DEBUG 2

对于所有可用的项目文件。

问题:我可以用这种方式在整个项目中定义宏函数,而不包括某种header使用 -include 或其他方式归档?

我的 makefile 中需要这样的东西:

/* not working code */
ifeq ($(MY_DEBUG),yes) 
EXTRACXXFLAGS += -Ddbg_print(...)=printf(##__VA_ARGS__)
endif

通常我会在一些 header 中定义这个宏函数,包括在整个项目中,但是这个特定的项目太大了,没有这样的 header.


如果到处都包含 header 文件,那就太好了:

Makefile

# this is in makefile
ifeq ($(MY_DEBUG),yes) 
EXTRACXXFLAGS += -DMY_DEBUG
endif

globally_included_header.h

// header, included all over the project
#ifdef MY_DEBUG
#    define dbg_print(...) printf(##__VA_ARGS__)
#else
#    define dbg_print(...)
#endif

您可以将 header 从命令行添加到所有源,方法是将其添加到 CXX 标志中:

-include "path/to/header.h"

编辑:

在您的特定情况下,您还可以将其传递给 CXX 标志以创建宏函数:

-D'dbg_print(...)=printf(__VA_ARGS__)'

在 windows 它对我有用 " 而不是 '

您可以将这样的 header 添加到所有带有 gcc -includecl -FI 的源文件中(Windows Visual Studio)。

只需将您的调试函数放在一个文件中,由 #ifdef 保护并在您的 make 命令中指定调试标志和文件。

总结一下:

在生成文件中

ifeq ($(MY_DEBUG),yes) 
EXTRACXXFLAGS += -DMY_DEBUG
endif
...
    $(CC) $(EXTRACXXFLAGS) -include globally_included_header.h ...

在globally_included_header.h

// header, included all over the project
#ifdef MY_DEBUG
#    define dbg_print(...) printf(##__VA_ARGS__)
#else
#    define dbg_print(...)
#endif