Ubuntn下的C语言编程与Makefile的初学
下载源的更改与gcc的安装和使用
更改为国内镜像软件源仓库
1.原文件的备份
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
2.进入sources.list修改下载源
sudo vim /etc/apt/sources.list
3.把下列代码替换到sources.list下
deb http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multivers
deb http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
gcc的安装和使用
1.gcc的安装
查看自己的版本
gcc --version
如果没有可以输入下列代码去下载
sudo apt install gcc
2.gcc的使用,创建一个输出为hello,world的C语言程序
首先在vim中创建编写一个名为hello.c的C语言程序,输入命令
gcc hello.c -o hello
此时系统中会生成hello的可执行文件,然后在输入命令
./hello
编写一个主程序main1.c 和一个子程序sub1.c,并在Linux下运行
解释:
子程序sub1.c 包含一个算术运算函数 float x2x(int a,int b),此函数功能为对两个输入整型参数做乘法运算,将结果做浮点数返回;
主程序main1.c,定义并赋值两整型变量,然后调用函数 x2x,将x2x的返回结果printf出来。
main1.c
#include<stdio.h>
float x2x(float a, float b);
float main() {
float a;float b;
scanf("%f%f",&a,&b);
printf("a=%f,b=%f\n",a,b);
printf("a*b=%f\n",x2x(a,b));
}
sub1.c
float x2x(float a, float b) {
float t=a*b;
return t;
}
将main1.c和sub1.c结合
建立一个新的C语言文件test1.c
#include<stdio.h>
#include"sub1.c"
float x2x(float a, float b);
float main() {
float a;float b;
scanf("%f%f",&a,&b);
printf("a=%f,b=%f\n",a,b);
printf("a*b=%f\n",x2x(a,b));
}
再使用gcc生成test1的可执行文件,并测试C语言的正确性
gcc test1.c -o test1
./test1
在Windows下运行的C语言程序
Makefile方式编程
使用vim创建一个名为makefile的文件
main1:main1.o sub1.o
gcc -o main main1.o sub1.o
main1.o:main1.c
gcc -c main1.c
sub1.o:sub1.c
gcc -c sub1.c
把main1.c和sub1.c的内容整合到main文件,然后输出main文件