#include <stdio.h>
int main(void)
{
printf(“Hello, world!n”);
return 0;
}
我们假定该代码存为文件‘hello.c’。要用 gcc 编译该文件,使用下面的命令:
$ gcc -g -Wall hello.c -o hello
默认情况下GCC 不会产生任何警告信息,选项 -Wall开启编译器几乎所有常用的警告──强烈建议你始终使用该选项。
多个c文件编译时为:
$ gcc -Wall hello.c hello_fn.c -o newhello
写一个简单的 makefile 文件:
输入make。不加参数调用make时,makefile文件中的第一个目标被建立,从而生成可执行文件‘hello’:$ makeCC=gcc
CFLAGS=-Wall
hello: hello.o hello_fn.o
clean:
rm -f hello hello.o hello_fn.o
gcc -Wall -c -o hello.o hello.c
gcc -Wall -c -o hello_fn.o hello_fn.c
gcc hello.o hello_fn.o -o hello
一个源文件被修改要重新生成可执行文件,简单地再次输入 make即可。通过检查目标文件和依赖文件的时间戳,程序 make 可识别哪些文件已经修改并依据对应的规则更新其对应的目标文件:
$ vim hello.c (打开编辑器修改一下文件)
$ make
gcc -Wall -c -o hello.o hello.c
gcc hello.o hello_fn.o -o hello
创建文件calc.c:
#include <math.h>
#include <stdio.h>int main (void)
{
double x = 2.0;
double y = sin (x);
printf (“The value of sin(2.0) is %fn”, y);
return 0;
}
尝试单独从该文件生成一个可执行文件将导致一个链接阶段的错误:
显式地指定它:$ gcc -Wall calc.c -o calc
/tmp/ccbR6Ojm.o: In function ‘main’:
/tmp/ccbR6Ojm.o(.text+0×19): undefined reference to ‘sin’
可执行文件包含主程序的机器码以及函数库‘libm.a’中 sin 对应的机器码。$ gcc -Wall calc.c /usr/lib/libm.a -o calc
为避免在命令行中指定长长的路径,编译器为链接函数库提供了快捷的选项‘-l’。例如,下面的命令
与我们上面指定库全路径‘/usr/lib/libm.a’的命令等价$ gcc -Wall calc.c -lm -o calc
尝试编译简单的 C++ 的经典程序 Hello world:
#include <iostream>
int main(int argc,char *argv[])
{
std::cout << “hello, world”<< std::endl;
return 0;
}
将文件保存为‘hello.cpp’,用 gcc 编译,结果如下:
$ gcc -Wall hello.cpp -o hello
/tmp/cch6oUy9.o: In function`__static_initialization_and_destruction_0(int, int)’:
hello.cpp:(.text+0×23): undefined reference to`std::ios_base::Init::Init()’
/tmp/cch6oUy9.o: In function `__tcf_0′:
hello.cpp:(.text+0×6c): undefined reference to`std::ios_base::Init::~Init()’
/tmp/cch6oUy9.o: In function `main’:
hello.cpp:(.text+0×8e): undefined reference to `std::cout’
hello.cpp:(.text+0×93): 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/cch6oUy9.o:(.eh_frame+0×11): undefined reference to`__gxx_personality_v0′
collect2: ld returned 1 exit status
出错了!!而且错误还很多,很难看懂,这可怎么办呢?在解释之前,我们先试试下面的命令:
$ gcc -Wall hello.cpp -o hello -lstdc++
噫,加上-lstdc++选项后,编译竟然通过了,而且没有任何警告。运行程序,结果如下:
$ ./hello
hello, world
通过上节,我们可以知道,-lstdc++ 选项用来通知链接器链接静态库libstdc++.a。而从字面上可以看出,libstdc++.a 是C++ 的标准库,这样一来,上面的问题我们就不难理解了──编译C++ 程序,需要链接 C++ 的函数库 libstdc++.a。
不过幸运的是,GCC 包含专门为 C++ 、Fortran等语言的编译器前端。于是,上面的例子,我们可以直接用如下命令编译:
$ g++ -Wall hello.cpp -o hello