代码之家  ›  专栏  ›  技术社区  ›  DHamrick

编译器#为g++和cl定义

  •  2
  • DHamrick  · 技术社区  · 17 年前

    我正在编写一个跨平台的程序。有几个地方我必须指定一个依赖于操作系统的调用。

    #ifdef WINDOWS
    ..do windows only stuff
    #endif
    #ifdef LINUX
    ..do linux only stuff    
    #endif
    

    cl-DWINDOWS程序.cpp

    g++-DLINUX程序.cpp

    我意识到我可以很容易地编写一个makefile或一个shell/批处理脚本来自动执行此操作。但默认情况下,我更喜欢使用与编译器相同的代码(如果存在的话)。

    5 回复  |  直到 17 年前
        1
  •  5
  •   Kredns    17 年前

    this 网站。

    • #define __HAVE_BUILTIN_SETJMP__ 1
    • #define __unix__ 1
    • #define unix 1
    • #define __i386__ 1
    • #define __SIZE_TYPE__ unsigned int
    • #define __ELF__ 1
    • #define __GNUC_PATCHLEVEL__ 3
    • #define __linux 1
    • #define __unix 1
    • #define __linux__ 1
    • #define __USER_LABEL_PREFIX__
    • #define linux 1
    • #define __STDC_HOSTED__ 1
    • #define __EXCEPTIONS 1
    • #define __GXX_WEAK__ 1
    • #define __WCHAR_TYPE__ long int
    • #define __gnu_linux__ 1
    • #define __WINT_TYPE__ unsigned int
    • #define __GNUC__ 3
    • #define __cplusplus 1
    • #define __DEPRECATED 1
    • #define __GNUG__ 3
    • #define __GXX_ABI_VERSION 102
    • #define i386 1
    • #define __GNUC_MINOR__ 2
    • #define __STDC__ 1
    • #define __PTRDIFF_TYPE__ int
    • #define __tune_i386__ 1
    • #define __REGISTER_PREFIX__
    • #define __NO_INLINE__ 1
    • #define _GNU_SOURCE 1
    • #define __i386 1
    • #define __VERSION__ "3.2.3 20030502 (Red Hat Linux 3.2.3-47.3)"

        2
  •  3
  •   George Phillips    17 年前

    最小 一组在代码中使用的已定义编译常量。因为你可能会从这样的事情开始:

    #if defined(_WIN32)
        // do windows stuff
    #endif
    #if defined(_linux)
        // linux stuff
    #endif
    

    #if defined(_WIN32) || defined(ming)
    

    #if defined(ming)
    #define _WIN32
    #endif
    

    #if defined(_WIN32) || defined(ming)
        #define PLAT_WINDOWS
    #endif
    

    只有了解地球上每个操作系统上每个编译器的每个版本,才能理解 哎呀,谁不这么做,但无论如何,任何改变都必须在各地进行测试,这很痛苦。

    所以,最好在makefile内部甚至外部有一些高级设置,上面写着“如果你在windows上,-DPLAT_windows”,然后完成它。

    当然,如果你在代码中使用最常用的函数和功能,所有这些都会被最小化。

        3
  •  2
  •   DHamrick    17 年前

    所有这些答案都非常好。对我有效的解决方案如下。

    #ifdef _WIN32
    
    #endif
    
    #ifdef linux
    
    #endif
    

    WIN32不是由cl定义的,但_WIN32是。

        5
  •  0
  •   Rahul    16 年前

    您可以将代码放在#ifndef#else块中,而不是为特定平台设置两个宏。例如:

    #ifndef _WIN32
    // linux specific code
    #else
    // windows specific code
    #endif
    

    使用此解决方案,ifndef-else块将确保您不会在两个#ifdef块之间意外添加代码(这两个块应该以相同的方式处理程序执行流)。

    或者别的什么。