文章更新於:2020-03-23
文章目錄
一、手動編譯鏈接單個C源文件
1、創建C源文件
注:此處創建名爲 hello.c
的源文件。
#include<stdio.h>
int main()
{
printf("hello,world!\n");
return 0;
}
2、編譯源文件
gcc -c hello.c
3、生成可執行文件
注:此處的 result
爲你想要輸出的可執行文件名。
gcc -o result hello.o
二、手動編譯鏈接多個C源文件
1、創建兩個C源文件
注:此處創建名爲 hello.c
和 hello2.c
的兩個源文件。
#include<stdio.h>
int main()
{
printf("hello,world!\n");
testfun(); //調用另一個源文件中的函數
return 0;
}
#include<stdio.h>
void testfun()
{
printf("\nThis is in hello2!\n");
}
2、編譯兩個源文件
注:此處也可使用 gcc -c *.c
來編譯多個C源文件。
gcc -c hello.c hello2.c
3、生成可執行文件
gcc -o result hello.o hello2.o
三、使用Makefile自動編譯鏈接
1、創建C源文件
注1:此處延續使用上述例子的兩個C源文件。
注2:創建名爲 hello.c
和 hello2.c
的兩個源文件。
#include<stdio.h>
int main()
{
printf("hello,world!\n");
testfun(); //調用另一個源文件中的函數
return 0;
}
#include<stdio.h>
void testfun()
{
printf("\nThis is in hello2!\n");
}
2、創建Makefile文件
注1:這裏的hello.o
、hello2.o
是要創建的兩個目標文件。
注2:result
爲要輸出的可執行文件名。
注3:gcc
行前面的空白是Tab鍵生成的。
main: hello.o hello2.o
gcc -o result hello.o hello2.o -lm
3、執行make生成可執行文件
4、加上參數清理中間文件(可選)
注1:如果不想要中間產生的*.o
文件,可在Makefile中加入清理參數。
注2:最後一行也可以寫成 rm -f *.o
。
main: hello.o hello2.o
gcc -o result hello.o hello2.o -lm
clean:
rm -f hello.o hello2.o