【发布时间】:2012-12-21 21:05:58
【问题描述】:
我想在 Windows 和 Linux 上编译并运行一份 C++ 代码。所以我需要使用条件编译(CC)。但是遇到了如何在大量代码文件中使用CC的问题。
比如,我有:
//A.cpp
#define _WINDOWS_
#ifdef _WINDOWS_
#include <windows.h>
//some code for windows
#else
#include <pthread.h>
//some code for linux
#endif
我还有 B.cpp、C.cpp...
我应该在每个文件中都写“#define _WINDOWS_”,还是有更好的方法?
我也尝试过这样做:
-
创建头文件Platform.h
#ifndef _PLAT_ #define _PLAT_ #define _WINDOWS_ #endif -
包含文件 Platform.h,如:
//A.cpp #include "Platform.h" #ifdef _WINDOWS_ #include <windows.h> //some code for windows #else #include <pthread.h> //some code for linux #endif -
编译时出错!可能在包含
<windows.h>之前包含"Platform.h"会导致错误。
【问题讨论】:
-
你最好使用
_WIN32而不是自己滚动。 -
我觉得您需要抽象工厂将您的代码分离到不同的平台? en.wikipedia.org/wiki/Abstract_factory_pattern
-
什么是编译错误?看起来它至少应该可以工作
-
当我将“WINDOWS”改为“WIN”时,编译成功。使用 _WIN32 对我有用。谢谢大家。
标签: c++ conditional-compilation