如果我们需要编译的文件包含其他的文件中的函数的时候,可以用gcc命令实现
文件的创建
创建第一个文件other1.c
void welcome() {
printf(“Welcome to the world of Linux\n”);
}
创建第二个文件other2.c
int add(int x, int y) {
return x+y;
}
int sub(int x, int y){
return x-y;
}
创建第三个文件app.c
之前创建的两个文件中没有main函数,只有在app.c中存在main函数,而且再app.c中使用到的函数是在other1.c 和other2.c中定义的。
#include <stdio.h>
void main(){
int a=15,b=3,c;
printf(“test in app\n”);
welcome();
c = add(a, b);
printf(“%d + %d = %d\n”, a, b, c);
c = sub(a, b);
printf(“%d - %d = %d\n”, a, b, c);
}
文件的编译
文件的编译用到了gcc命令的使用
只需要在命令行模式中的gcc命令下输入我们用到的所有的文件即可。gcc other1.c other2.c app.c -o app
文件的运行
在命令行模式中输入:./app
即可运行编译通过的文件。
头文件
在正常的C项目实现的时候,通常会有头文件。
什么是头文件呢, 头文件就是声明会用到的库,头文件,和一些函数的声明等。
头文件的创建
创建一个头文件other1.h
#ifndef OTHER1_H
#define OTHER1_H
#include <stdio.h>
void welcome(); //用到的函数的声明。
#endif
创建一个头文件other2.h
#ifndef OTHER2_H
#define OTHER2_H
#include <stdio.h>
int add(int, int);
int sub(int, int);
#endif
要将other1.c 和 other2.c文件做一下修改。
#include “other1.h”
void welcome() {
printf(“Welcome to the world of Linux\n”);
}
#include “other2.h”
int add(int x, int y) {
return x+y;
}
int sub(int x, int y){
return x-y;
}
对于app.c的修改
#include “other1.h”
#include “other2.h”
void main(){
int a=15,b=3,c;
printf(“test in app\n”);
welcome();
c = add(a, b);
printf(“%d + %d = %d\n”, a, b, c);
c = sub(a, b);
printf(“%d - %d = %d\n”, a, b, c);
}
编译和运行的方法没有改变。