C ++上的跨平台编程

时间:2012-04-02 14:00:18

标签: c++ cross-platform c-preprocessor

我想让程序工作并在 WIN \ Linux 中编译 我想获得一些关于我的程序运行的 OS 的信息 而且我想要一个变量来决定我想要执行的代码。

我想到了一个预处理代码,可以输入我所描述的控制变量 所以,我必须有类似的东西:

#  //a preprocess code to detect the os
# define controllingVar // ?

我使用C ++;

2 个答案:

答案 0 :(得分:3)

您可以检查是否已定义WIN32宏:

#ifdef WIN32
   // do windows stuff
#else
   // do GNU/Linux stuff
#endif

请注意,在某些编译器上,您可能还需要检查_WIN32,如wikipedia中所述。

举个例子:

#ifdef WIN32
   void foo() {
       std::cout << "I'm on Windows!\n";
   }
#else
   void foo() {
       std::cout << "I'm on GNU/Linux!\n";
   }
#endif

修改:因为您要求为每个操作系统提供不同的main,所以这是一个示例:

int main() {
#ifdef WIN32
   // do whatever you want when executing in a Windows OS
#else
   // do the same for GNU/Linux OS.
#endif
}

您也可以使用不同的main

#ifdef WIN32
   int main() {
       //windows main
   } 
#else
   int main() {
       //GNU/Linux main
   } 
#endif

答案 1 :(得分:1)

您可以使用(编译器特定的)预处理器宏(如WIN3​​2等)来推断您的代码正在编译的平台。没有简单的方法来推断您的程序正在运行的平台(除了它最有可能在它编译的平台上运行) - 您将需要执行特定于平台/操作系统的调用这一点。

你可以这样做:

#ifdef WIN32 // compiler specific, WIN32 is defined in Visual Studio
  // Windows specific code
  // include Windows specific headers
  int controllingVar = 0; // 0 - Windows
#else
  // For everything else
  // Here: assume Unix/Linux
  // include Linux specific headers
  int controllingVar = 1; // 1 - non-Windows
#endif

在此之后,您可以在代码中引用controllingVar。如果程序是针对Windows编译的,则controllingVar的值为0,否则为1(并且您可以采用Linux的假设)。

#ifdef部分启用条件编译 - Windows特定块中的代码仅在为Windows编译时编译,其他情况在任何其他情况下编译。

请注意,这实际上需要重复编码,维护和测试工作,因此请尽量将最重要的代码放在条件块中以及任何非平台特定的代码之外。