Linux利器:使用 gcc 編程C程序

文章更新於: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.chello2.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.chello2.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.ohello2.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

清楚中間文件

四、Enjoy!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章