gcc与g++编译区别
gcc和g++的主要区别
1. 对于 *.c和*.cpp文件,gcc分别当做c和cpp文件编译(c和cpp的语法强度是不一样的)
2. 对于 *.c和*.cpp文件,g++则统一当做cpp文件编译
3. 使用g++编译文件时,g++会自动链接标准库STL,而gcc不会自动链接STL
4. gcc在编译C文件时,可使用的预定义宏是比较少的
5. gcc在编译cpp文件时/g++在编译c文件和cpp文件时(这时候gcc和g++调用的都是cpp文件的编译器),会加入一些额外的宏,这些宏如下:
我以extern关键字的用法来说明gcc和g++:
未加extern "C"声明时的链接方式:
//模块A头文件 moduleA.h
#idndef _MODULE_A_H
#define _MODULE_A_H
int foo(int x, int y);
#endif
在模块B中调用该函数:
//模块B实现文件 moduleB.cpp
#include"moduleA.h"
foo(2,3);
实际上,在链接阶段,连接器会从模块A生成的目标文件moduleA.obj中找_foo_int_int这样的符号!!!,显然这是不可能找到的,因为foo()函数被编译成了_foo的符号,因此会出现链接错误。
例:
/**************func.h*******************/ #ifndef FUNC_H #define FUNC_H void print(int i); #endif
/*************************func.c********************/ #include <stdio.h> #include "func.h" void print(int i) { printf("i = %d\n", i); }
/*******************test.cpp*****************/ #include <iostream> extern "C" { #include "func.h" } int main(void) { print(3); return 0; }
我的makefile文件是这么写的
/*****************makefile*****************/ test1:main.o g++ -o test1 main.o func.o main.o:test.cpp func.o func.h g++ -c test.cpp -o main.o func.o:func.c func.h gcc -c func.c -o func.o clean: rm func.o main.o test1
我在makefile中func.o是用gcc编译出来的,而其它的编译都是g++,因此就会出现上面的问题(如果test.cpp中不用extern "C"的话)
但是假如我的makefile这么写
test1:main.o g++ -o test1 main.o func.o main.o:test.cpp func.o func.h g++ -c test.cpp -o main.o func.o:func.c func.h g++ -c func.c -o func.o //现在我用g++来编译 clean: rm func.o main.o test1
那么test.cpp重的extern "C"还有必要么?
这时候要去掉的,不然编译就会出现错误了,原理就是gcc和g++的区别

浙公网安备 33010602011771号