如何编写确定其编译器的程序

How to write a program that determines its compiler

本文关键字:编译器 程序 何编写      更新时间:2023-10-16

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

不能使用预处理器指令。

在头脑中,仅用于将任何字符的大小与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++

那里,有更好的方法吗?

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

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

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

所以它包含您使用的字符与整数的差异,但也包括例如

更改:在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

相关文章: