【问题标题】:How to write a program that determines its compiler [duplicate]如何编写确定其编译器的程序[重复]
【发布时间】:2014-03-21 23:59:36
【问题描述】:

需要写一个C程序。如果在 C 语言编译器中运行,程序应打印“C”。如果它在编译器 C++ 中运行,它应该打印“C++”。

不能使用预处理指令。

in head 仅用于将任何字符的大小与char 大小进行比较,例如:

sizeof(char)==sizeof('a')

这里是如何工作的:

// C code:
#include <stdio.h>
int main()
{
    printf("%s", (sizeof(char)==sizeof('a') ? "C++" : "C"));
    return 0;
}

输出: C

// C++ code:
#include <stdio.h>
int main()
{
    printf("%s", (sizeof(char)==sizeof('a') ? "C++" : "C"));
    return 0;
}

输出: C++

还有更好的方法吗?

【问题讨论】:

  • 选择链接问题的任何答案。
  • 你可以改用sizeof('a') == 1,因为sizeof(char) == 1的定义。
  • 这是一种合理的方式来完成这项工作(至少如果您也打印换行符)。它比我对标题所期望的要简单得多,即确定哪个编译器名称和版本号。

标签: c++ c


【解决方案1】:

标准http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf 包含关于 C 和 C++ 之间差异的附录

因此它包含您使用的 char 与 int 的差异,但也包含例如

更改:在 C++ 中,类声明将类名引入范围 声明并隐藏任何对象、函数或其他声明的地方 该名称在封闭范围内。 在 C 中,结构标记名称的内部范围声明从不隐藏 外部范围内的对象或函数的名称

示例:(来自标准)

int x [99];
void f () {
     struct x { int a ; };
     sizeof (x ); /∗ size of the array in C ∗/
                  /∗ size of the struct in C++ ∗/
}

gcc 在我的机器上给了 396 和 g++ 4

【讨论】:

    【解决方案2】:

    您可以检查__cplusplus 宏来查看您是否被编译为c++。

    #include <stdio.h>
    
    int main()
    {
        printf("%s\n",
    #if __cplusplus
                "C++"
    #else
                "C"
    #endif
              );
    }
    

    【讨论】:

    • Preprocessor directives can not be used.。但你不妨做个幽默的#if true 把戏。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2012-06-05
    • 2014-11-18
    • 2021-08-13
    相关资源
    最近更新 更多