鉴于需要支持多个环境的 C 项目,如何使用预处理器来强制确定只定义了一个环境?
我已经可以做了:
#if defined PROJA (blah blah blah) #elif defined PROJB (etc) #else #error "No project defined" #endif
但是,所有这一切都告诉我是否定义了0个项目。如果一些有用的灵魂定义项目A和项目B,预处理器将只假设项目A.但是,从我的角度来看,正确的行为是标记错误。
当然,只定义了2个项目,这个问题很简单。我如何用200解决它?
答案 0 :(得分:3)
类似的东西:
#if defined PROJA
#ifdef HAVE_PROJ
#error
#endif
#define HAVE_PROJ
#endif
#if defined PROJB
#ifdef HAVE_PROJ
#error
#endif
#define HAVE_PROJ
#endif
#ifndef HAVE_PROJ
#error No project selected (you need to define PROJA, PROJB, or ...)
#endif
答案 1 :(得分:2)
也许有不同的文件
include_proja.h
include_projc.h
然后使用您的Makefile或其他任何内容来包含正确的文件。然后,您可以使用代码生成200个不同的文件,并在编译时包含正确的文件。
这种是构建系统的目的。如果你正在用宏做这样奇怪的事情......在源代码之外找一个更好的方法。
每个文件都可以(请原谅这里的详细程度)
#define A_PROJECT_INCLUDE_WAS_INCLUDED
然后再做
#ifndef A_PROJECT_INCLUDE_WAS_INCLUDED
#error "No project include"
#endif
但是一些遗漏的符号无论如何都会破坏它。
祝你好运
答案 2 :(得分:2)
试试这个
#define ENV_UNKNOWN 0
#define ENV_MACOSX 1
#define ENV_LINUX 2
#define ENV_WIN32 3
/* and so on */
#ifndef ENVIRONMENT
/* no environment given, default to something (perhaps) */
#define ENVIRONMENT ENV_UNKNOWN
#endif
/* and now the environment specific parts */
#if (ENVIRONMENT == ENV_MACOSX)
#include "macosx_port.h"
#endif
#if (ENVIRONMENT == ENV_LINUX)
#include "linux_port.h"
#endif
#if (ENVIRONMENT == ENV_WIN32)
#include "win32_port.h"
#endif
#if (ENVIRONMENT == ENV_UNKNOWN)
#error You have to specify the ENVIRONMENT.
#endif
现在,您可以在命令行中指定要编译的环境,如下所示:
cc -DENVIRONMENT=2 ...
另一种方法是根据您正在编译的环境,在构建系统中包含/链接不同的模块。
答案 3 :(得分:2)
#if defined PROJA
bool one_project_defined = true;
#endif
#if defined PROJB
bool one_project_defined = true;
#endif
#if defined PROJC
bool one_project_defined = true;
#endif
#if defined PROJD
bool one_project_defined = true;
#endif
one_project_defined; // Won't compile in wrong builds
答案 4 :(得分:0)
嵌套ifs的问题在于你最终会为n个项目进行n ^ 2个不同的测试。
在这种情况下,您只需要一些会产生编译时错误的表达式。也许:
#ifdef PROJA
#define PROJA-TEST "
#else
#define PROJA-TEST ""
#endif
对于B,C等,等等。
然后:
const char *test_only_one_project = PROJA-TEST PROJB-TEST PROJC-TEST " "More than one project is defined!";
编辑:...当然这只测试了奇数个项目的定义。但这应该有效:
#ifdef PROJA
#define PROJA-TEST (
#endif
等等,然后
const char *test_only_one_project = PROJA-TEST PROJB-TEST PROJC-TEST "More than one project is defined!" );
答案 5 :(得分:-1)
也许你可以这样做:
#if PROJ==A
(blah blah blah)
#elif PROJ==B
(etc)
#else
#error "No project defined"
#endif