Linux-多文件编译


如果我们需要编译的文件包含其他的文件中的函数的时候,可以用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);

} 

编译和运行的方法没有改变。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值