C++ 分离编译 多个文件

来源:互联网 发布:php代理ip访问网站 编辑:程序博客网 时间:2024/06/06 18:41

一个很大程序,往往是若干函数构成。

可每修改一个函数,要把所有的子函数都重新编译一遍太麻烦,据卜胖子说,很可能是太花时间。

于是,将各个子函数分开编译,现在,写一个小例子,记录一下。

有四个文件。

work_fact.cpphead_all.hfun_fact.cpp fun_add.cpp 

其中,

work_fact.cpp
是主函数。

fun_fact.cpp
是一个函数文件,求一个数的阶乘。

fun_add.cpp
求两个数的和


work_fact.cpp

调用fun_fact.cpp当中的mm_fact函数。j=mm_fact(n1);k=mm_fact(n2);

调用fun_add.cpp当中的mm_add函数。l=mm_add(j,k);


除了work_fact.cpp在文件最一开始声明两个函数。具体的内容,在各自的文件当中。

两个函数文件与work_fact.cpp之间,是通过head_all.h文件来沟通。具体的,是由sh_run.sh实现的。


g++ -c work_fact.cppg++ -c fun_fact.cppg++ -c fun_add.cppg++ work_fact.o fun_fact.o fun_add.o -o main

其中,最后一句是将两个函数连接起来,每次,生成对应的.o文件就好。


work_fact.cpp

# include <iostream># include "head_all.h"using namespace std;int mm_fact(int);int mm_add(int ,int );int main(){int n1=6,n2=4;int j = mm_fact(n1);int k = mm_fact(n2);int l = mm_add(j,k);cout << n1 << "! is " << j << endl;cout << n2 << "! is " << k << endl;cout << "sum of " << n1 << "! and " << n2 << "! is " << l << endl;return 0;}

fun_fact.cpp

# include <iostream># include "head_all.h"int mm_fact (int val){int ret = 1;while(val > 1)ret *= val--;return ret;}


fun_add.cpp

# include <iostream># include "head_all.h"int mm_add (int val1, int val2){int out = 0;out = val1 + val2;return out;}

head_all.h

int mm_fact(int);int mm_add(int );

运行sh_run.sh。会有三个*.o文件。

fun_add.o  fun_fact.o  work_fact.o


最后,会有一个主程序。main

./main

结果:

6! is 7204! is 24sum of 6! and 4! is 744

差不多了。


0 0
原创粉丝点击