一 点睛
gcc编译器的基本语法格式
gcc [选项] 准备编译的文件 [选项] [目标文件]
准备编译的文件:除了C或CPP源文件外,也可能是汇编源码文件(.s文件)。
目标文件:如果没有指明,就自动生成a.out。
常用使用方式:
gcc test.c -o test
简洁方式:
gcc test
二 使用gcc编译一个C程序
1 源代码
#include <stdio.h>
int main(int argc,char *argv[])
{
printf("hello, boy \n" );
return 0;
}
2 编译和运行
[root@localhost test]# gcc test.c -o test
[root@localhost test]# ./test
hello, boy
三 使用gcc编译一个不需要C++库的C++程序
1 源代码
#include <stdio.h>
int main()
{
bool b=false; //如果文件命名为test.c就会报错,因为C语言没有bool类型
printf("hello, boy \n" );
return 0;
}
2 编译和运行
[root@localhost test]# gcc test.cpp -o test
[root@localhost test]# ./test
hello, boy
四 使用gcc编译一个需要C++库的C++程序
1 源代码
#include <iostream>
using namespace std; //命名空间
int main()
{
bool b=false; //如果文件命名为test.c就会报错,因为C语言没有bool类型
cout<<"hello,boy \n"; //cout是std中的对象,用于打印输出
return 0;
}
2 错误的方式编译
[root@localhost test]# gcc test1.cpp -o test1
/tmp/cchgDKd3.o: In function `main':
test1.cpp:(.text+0x12): undefined reference to `std::cout'
test1.cpp:(.text+0x17): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
/tmp/cchgDKd3.o: In function `__static_initialization_and_destruction_0(int, int)':
test1.cpp:(.text+0x45): undefined reference to `std::ios_base::Init::Init()'
test1.cpp:(.text+0x54): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
3 正确的方式编译
[root@localhost test]# gcc test1.cpp -lstdc++ -o test1
[root@localhost test]# ./test1
hello,boy
4 说明
因为用到了C++标准库里面的内容,所有需要用gcc的选项-l来链接C++标准库stdc++,如果没有这个选项,就会报错。