这取决于您在 makefile 中具体更改的内容。gcc
/ g++
实际上只是一个前端驱动程序,它根据您提供的选项调用实际的编译器和/或链接器。
如果您将编译器调用为gcc
:
- it will compile根据文件扩展名作为 C 或 C++ (
.c
, or .cc
/ .cpp
);
- it will link与 C 一样,即它不会引入 C++ 库,除非您专门添加其他参数来执行此操作。
如果您将编译器调用为g++
:
- it will compile作为 C++,无论文件扩展名是否为
.c
or .cc
/ .cpp
;
- it will link作为 C++,即自动引入标准 C++ 库。
(see GCC 文档的相关部分).
这是一个简单的程序,用于检测它是否已编译为 C 或 C++。
(它利用了字符常量的大小为int
在 C 语言中,或char
在C++中。sizeof(char)
根据定义为 1;sizeof(int)
通常会更大 - 除非您使用的是 >= 16 位字节的模糊平台,但您可能不会。)
我已经这样称呼它了test.c
并将其复制为test.cc
还有:
File test.c
#include <stdio.h>
int main(void)
{
printf("I was compiled as %s!\n", sizeof('a') == 1 ? "C++" : "C");
return 0;
}
Copy
cp test.c test.cc
编译和链接test.c
with gcc
, and test.cc
with g++
,按预期工作:
$ gcc -o test test.c
$ ./test
I was compiled as C!
$ g++ -o test test.cc
$ ./test
I was compiled as C++!
编译和链接test.cc
with gcc
不起作用:它将代码编译为 C++,因为文件以.cc
,但在链接阶段失败:
gcc -o test test.cc
Output:
/tmp/ccyb1he5.o:(.eh_frame+0x11): undefined reference to `__gxx_personality_v0'
collect2: ld returned 1 exit status
我们可以通过单独编译来证明gcc
,并与g++
(拉入正确的库):
$ gcc -c test.cc
$ g++ -o test test.o
$ ./test
I was compiled as C++!
...gcc
将代码编译为 C++ 而不是 C,因为它有一个.cc
文件扩展名。
Whereas g++
does not编译.c
文件为普通 C:
$ g++ -o test test.c
$ ./test
I was compiled as C++!