C 预处理器:基于定义包含

sle*_*ica 3 macros c-preprocessor preprocessor-directive

如何根据定义的字符串的值包含一个文件或另一个文件?

这不起作用:

#define VAR VALUE_A

#if VAR == "VALUE_A"
    #include "a.h"
#elif VAR == "VALUE_B"
    #include "b.h"
#endif
Run Code Online (Sandbox Code Playgroud)

如果它很重要,我实际上并没有定义VAR,我只是通过 命令行将它传递下来gcc -D NAME=VALUE

5go*_*der 5

==运算符不比较字符串。但是您还有其他几个选项来配置您的包含内容。除了其他答案中已经提到的解决方案之外,我喜欢这个解决方案,因为我认为它非常不言自明。

/* Constant identifying the "alpha" library. */
#define LIBRARY_ALPHA 1

/* Constant identifying the "beta" library. */
#define LIBRARY_BETA 2

/* Provide a default library if the user does not select one. */
#ifndef LIBRARY_TO_USE
#define LIBRARY_TO_USE LIBRARY_ALPHA
#endif

/* Include the selected library while handling errors properly. */
#if LIBRARY_TO_USE == LIBRARY_ALPHA
#include <alpha.h>
#elif LIBRARY_TO_USE == LIBRARY_BETA
#define BETA_USE_OPEN_MP 0  /* You can do more stuff than simply include a header if needed. */
#include <beta.h>
#else
#error "Invalid choice for LIBRARY_TO_USE (select LIBRARY_ALPHA or LIBRARY_BETA)"
#endif
Run Code Online (Sandbox Code Playgroud)

您的用户现在可以使用以下命令进行编译:

/* Constant identifying the "alpha" library. */
#define LIBRARY_ALPHA 1

/* Constant identifying the "beta" library. */
#define LIBRARY_BETA 2

/* Provide a default library if the user does not select one. */
#ifndef LIBRARY_TO_USE
#define LIBRARY_TO_USE LIBRARY_ALPHA
#endif

/* Include the selected library while handling errors properly. */
#if LIBRARY_TO_USE == LIBRARY_ALPHA
#include <alpha.h>
#elif LIBRARY_TO_USE == LIBRARY_BETA
#define BETA_USE_OPEN_MP 0  /* You can do more stuff than simply include a header if needed. */
#include <beta.h>
#else
#error "Invalid choice for LIBRARY_TO_USE (select LIBRARY_ALPHA or LIBRARY_BETA)"
#endif
Run Code Online (Sandbox Code Playgroud)