C+±–linux运行
1. 在linux下使用gcc/g++编译多个.h .c 文件
main.cpp :
#include <iostream>
#include <myhead.h>
using namespace std;
int main(){//fun_head();cout<<"in main"<<endl;int x=100;int y=200;cout<<"sum : "<<sum(x,y);return 0;
}
myhead.h
#ifndef __myhead_h
#define __muhead_h
void print();
int sum(int a,int b);
#endif
myhead.cpp
#include "myhead.h"
#include <iostream>
using namespace std;
void print(){cout<<"in fun head"<<endl;
}
int sum(int a,int b){return a+b;
}
如果直接编译:
>> g++ main.cpp -o main
main.cpp:2:20: fatal error: myhead.h: No such file or directory
compilation terminated.
通过 -I 选项 链接上去。重新编译:
>> g++ main.cpp -o main -I ../myinclude/
/tmp/ccH3BlLo.o: In function `main':
main.cpp:(.text+0x3e): undefined reference to `sum(int, int)'
collect2: error: ld returned 1 exit status
sum函数是在myhead.cpp文件上面定义的。也就是需要把myhead.cpp文件编译一下。
>> g++ -c myhead.cpp -o myhead.o
再次编译:
>> g++ main.cpp -o main -I ../myinclude/ ../myinclude/myhead.o
运行:
./main