我们可以从源文件中访问编译器路径吗?

Can we access the compiler path from within a source file?

我正在寻找一种以编程方式访问正在编译当前源文件的编译器的 路径 的方法(我假设这里有类似宏的东西,想想 __FILE__ 和朋友)。 理想情况下是独立于编译器的东西,但我也不介意特定于编译器的扩展(在这种情况下最好是 gcc),如果可能的话。

专门查看 gcc,我查找了 predefined macros 但找不到任何内容。 我正在寻找的是这样的:

printf("The compiler that compiled this file is located at %s\n", __COMPILERPATH__);
//  -> "The compiler that compiled this file is located at /usr/bin/gcc"

但是没有__COMPILERPATH__

C++ 中没有标准方法。

一种简单的方法是在编译时将传递作为宏定义传递给编译器路径。其语法是特定于编译器的,但构建系统生成器可以提供帮助。

如果 std::embed proposal 被接受为未来的标准,那么下面的技巧可能会奏效:std::embed("/proc/self/cmdline")。但是,这是 Linux 特定的。

如果您正在使用 gcc 编译 C 程序,您可以执行以下操作:

gcc -DCOMPILER_PATH="$(gcc --print-prog-name=cc1)" ...

例如:

文件:idgcc.c

#include <stdio.h>

#define STRINGIFY_(x) #x
#define STRINGIFY(x) STRINGIFY_(x)

int main(void) {
  printf("Compiled with gcc v%d.%d.%d at %s\n",
         __GNUC__,
         __GNUC_MINOR__,
         __GNUC_PATCHLEVEL__,
         STRINGIFY(COMPILER_PATH));
}

构建并运行

$ gcc-10 -DCOMPILER_PATH="$(gcc --print-prog-name=cc1)" idgcc.c && ./a.out
Compiled with gcc v10.1.0 at /usr/lib/gcc/x86_64-1-gnu/7/cc1