Macros C预处理器:基于定义的包含
如何根据已定义字符串的值包含文件或其他文件 这不起作用:Macros C预处理器:基于定义的包含,macros,c-preprocessor,preprocessor-directive,Macros,C Preprocessor,Preprocessor Directive,如何根据已定义字符串的值包含文件或其他文件 这不起作用: #define VAR VALUE_A #if VAR == "VALUE_A" #include "a.h" #elif VAR == "VALUE_B" #include "b.h" #endif 如果它很重要,我实际上并没有定义VAR,而是通过gcc-D NAME=VALUE从命令行传递它,您可以使用#ifdef或#ifndef进行条件包含 #ifdef VALUE_A #include "a.h" #end
#define VAR VALUE_A
#if VAR == "VALUE_A"
#include "a.h"
#elif VAR == "VALUE_B"
#include "b.h"
#endif
如果它很重要,我实际上并没有定义VAR
,而是通过gcc-D NAME=VALUE
从命令行传递它,您可以使用#ifdef
或#ifndef
进行条件包含
#ifdef VALUE_A
#include "a.h"
#endif
#ifdef VALUE_B
#include "b.h"
#endif
我能想到的最接近的可能性是利用第三种形式的
#include
指令(C11§6.10.2/4),即使用值定义VAR
,它保存实际的头文件名:
#define VAR "a.h"
然后只需使用以下命令:
#include VAR
=
运算符不比较字符串。但是您还有几个其他选项来配置您的include。除了其他答案中已经提到的解决方案之外,我喜欢这个,因为我认为它是不言自明的
/* 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
+1为什么投反对票?如果@grzegorzzpetkowski不是更快的话,我自己也会提出这个建议。这是一种非常灵活的技术,对于在库中提供钩子特别有用。