linux c多文件编译,linux C下多文件编译,以及Makefile的使用

由于在C语言中,不能把所有的代码都放在一个.c文件里面,这样这个.c文件会很大,而且代码维护起来会很麻烦。

于是在网上找了些C语言多文件编程的示例,记录下我的学习过程。

我们可以把我们的代码按功能进行划分,一些源文件存放函数的实现,一些头文件声明这些函数,这样代码会更有条理。

头文件的大致格式:

#ifndef _ABC_H_

#define _ABC_H_

//以上代码是为了防止这个头文件被多次包含,确保名字唯一

//宏定义

#define _MAX 100

//结果体声明

typedef struct{

int a;

}ABC;

//函数声明

void abcfun(void);

...

#endif

接下来介绍下多文件编程的小例子

功能:在main.c里面调用其他两个源文件里面的函数,然后输出字符串。

1、main.c

#include"mytool1.h"

#include"mytool2.h"

int main(int argc,char** argv)

{

mytool1_printf("hello.");

mytool2_print("hello");

return 1;

}

2、 mytool1.h     mytool1.c

//mytool1.h

#ifndef _MYTOOL_1_H

#define _MYTOOL_2_H

void mytool1_printf(char* print_str);

#endif

//mytool1.c

#include"mytool1.h"

#include

void mytool1_printf(char* print_str)

{

printf("This is mytool1 print %s\n",print_str);

}

3、 mytool2.h mytool2.c

//mytool2.h

#ifndef _MYTOOL_2_H

#define _MYTOOL_2_h

void mytool2_print(char* print_str);

#endif

//mytool2.c

#include "mytool2.h"

#include

void mytool2_print(char* print_str)

{

printf("This is mytool2 print %s\n",print_str);

}

在linux下,把这几个文件放在同一个目录下,然后在shell中输入

gcc -c main.c

gcc -c mytool1.c

gcc -c mytool2.c

gcc -o main main.o mytool1.o mytool2.o

就可以生成可执行文件 main

关于 Makefile 还没学清楚,学清楚了补充。

引用:

http://blog.163.com/m13591120447_1/blog/static/21637918920132365724538/

http://soft.chinabyte.com/os/12/11584512.shtml

原文:http://www.cnblogs.com/tqianly/p/4374735.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值