以hello world为例。
#include<stdio.h>
int main()
{
printf("hello world!\n");
return 0;
}
gcc hello.c 生成a.out为可执行文件 ./a.out 输出:hello world!;
如果要指定可执行文件名:gcc hello.c -o hello.out ----------->生成 hello.out
多个源文件:max.c min.c 以及hello.c
int max(int a, int b)
{
if(a > b)
{
return a;
}
else
{
return b;
}
}
int min(int a, int b)
{
if(a < b)
{
return a;
}
else
{
return b;
}
}
#include<stdio.h>
// #include"max.h"
// #include"min.h"
int main()
{
int i = 33, j = 30;
int maxNum = max(i, j);
int minNum = min(i, j);
printf("the max value is %d \n the min num is %d \n", maxNum, minNum);
return 0;
}
输入:gcc hello.c max.c min.c -o main.out --------main.out (gcc 版本比较高没有报错)
./main.out
输出:
the max value is 33
the min num is 30
这样不方便,每次都要编译链接max.c 和min.c 两个文件,当然可以使用#include"max.c"但是相当于复制max.c的内容到hello.c中,所以直接使用头文件形式引入:
编辑头文件:
max.h
int max(int a, int b);
min.h
int min(int a, int b);
先将max.c 和 min.c生成静态库:
gcc max.c -o max.o
gcc min.c -o min.o
在hello.c中:
#include<stdio.h>
#include"max.h"
#include"min.h"
int main()
{
int i = 33, j = 30;
int maxNum = max(i, j);
int minNum = min(i, j);
printf("the max value is %d \n the min num is %d \n", maxNum, minNum);
return 0;
}
然后:gcc hello.c max.o min.o 会生成:a.out可执行文件,这样别人看到头文件就知道函数max和min的参数以及返回值类型。
makefile编写:
输入:make -v 查看make版本。(sudo apt-get install make 安装)
vim Makefile
#this is makefile //注释
hello.out:max.o min.o hello.c //生成hello.out 需要max.o min.o hello.c 三个文件,下面一条是命令
gcc max.o min.o hello.c -o hello.out
max.o:max.c //生成max.o需要max.c文件 min.o 同理
gcc -c max.c
min.o:min.c
gcc -c min.c
Makefile文件就这么编写,然后输入:
make
生成:
first.c hello.c hello.out Makefile max.c max.h max.o min.c min.h min.o