通常我们建立一个程序的基本步骤如下:
标志-c表示gcc在编译阶段完成后就停止,即会生成main.o
实例1:
#include <stdio.h>
int odd(int n)
{
if(1 == n%2) return 1;
return 0;
}
代码存在ex_1.c中,则编译的代码如下:
qiya@ubuntu:~$ls
ex_1.c
qiya@ubuntu:~$gcc -c ex_1.c
qiya@ubuntu:~$ls
ex_1.c ex_1.o
qiya@ubuntu:~$
ex_1.o目标代码文件包含了机器代码,即可以处理机器上运行的指令,但一个目标代码是不能直接被执行的,
必须经过链接操作变成一个可执行代码程序。而链接可以是多个目标代码组织在一起安排它们形成一个可执行文件,
目标代码可以来自多个源代码文件。
实例2:
#include <stdio.h>
int odd(int n);
int main()
{
int i;
while(1)
{
printf(">");
scanf("%d", &i);
if(odd(i)) printf("%d is odd number!\n", i);
else printf("%d is not odd number!\n", i);
}
return 0;
}
上面代码保存为ex_2.c
下面来进行编译和链接:
qiya@ubuntu:~$gcc -c ex_1.c
qiya@ubuntu:~$gcc -c ex_2.c
qiya@ubuntu:~$ls
ex_1.c ex_1.o ex_2.c ex_2.o
qiya@ubuntu:~$gcc ex_1.o ex_2.o
qiya@ubuntu:~$ls
a.out ex_1.c ex_1.o ex_2.c ex_2.o
qiya@ubuntu:~$
建立了可执行文件a.out
qiya@ubuntu:~$./a.out
>3
3 is odd number!
>4
4 is not odd number!