gpt4 book ai didi

macros - C预处理器: include based on define

转载 作者:行者123 更新时间:2023-12-03 00:01:05 26 4
gpt4 key购买 nike

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

这不起作用:

#define VAR VALUE_A

#if VAR == "VALUE_A"
#include "a.h"
#elif VAR == "VALUE_B"
#include "b.h"
#endif

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

最佳答案

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

/* 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

您的用户现在可以使用以下方式进行编译:

$ cc -DLIBRARY_TO_USE=LIBRARY_BETA whatever.c

关于macros - C预处理器: include based on define,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26198031/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com