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!

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值