linux (ubuntu)下C语言入门(编译,make)

3 篇文章 0 订阅

以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 








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值