g++多文件编译

头文件:A.h


void test();

源文件:A.cpp

#include <iostream>
#include<thread>
#include<chrono>
#include<clocale>

#include "boost/date_time/gregorian/gregorian.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"


using namespace std;
using namespace boost;
using namespace boost::gregorian;
using namespace boost::posix_time;


void test()
{
	date d = day_clock::local_day();
	date_facet* dfacet = new date_facet("%Y年%m月%d日");
	cout.imbue(locale(cout.getloc(), dfacet));
	cout << d << endl;

	ptime tp = microsec_clock::local_time();
	time_facet* tfacet = new time_facet("%Y年%m月%d日%H点%M分%S%F秒");
	cout.imbue(locale(cout.getloc(), tfacet));
	cout << tp << endl;

}

main函数所在文件:test.cpp

#include "A.h"


int main()
{
   test();
   return 0;
}

手动编译:

一步编译:

g++ -o test.o A.cpp test.cpp -std=c++11

分开编译:

g++ -c A.cpp -std=c++11

g++ -c test.cpp

g++ A.o test.o -o test.out


运行:./test.out



采用makefile编译:

test:A.o test.o
	g++ -o test A.o test.o
test.o:A.h test.cpp
	g++ -c test.cpp
A.o:A.cpp
	g++ -c A.cpp -std=c++11
clean:
	rm test A.o test.o

引入变量:

objects=A.o test.o
test:$(objects)
	g++ -o test $(objects)
test.o:A.h test.cpp
	g++ -c test.cpp
A.o:A.cpp
	g++ -c A.cpp -std=c++11
clean:
	rm test $(objects)

自动推导:

objects=A.o test.o
test:$(objects)
	g++ -o test $(objects)
test.o:A.h                        //省略编译命令和test.cpp
A.o:A.cpp
	g++ -c A.cpp -std=c++11   //因为要使用c++11编译,所以显示给出,这两句。否则,和上一行可以省略
clean:
	rm test $(objects)


1.附加库在链接阶段
2.不属于项目的头文件,如果没在默认寻找目录中,使用 -L指定,在依赖中不用写
3.使用mysql的库要apt-get install libmysql++-dev



objects=main.o parsexml.o tinyxml2.o opfile.o opmysql.o stringex.o pathx.o timex.o

logtoo_srvd_bin=../build/bin


logtoo_srvd:$(objects)
	g++ -o $(logtoo_srvd_bin)/logtoo_srvd $(objects) -L /usr/local/lib -lmysqlclient
	rm $(objects)

main.o:parsexml.h opmysql.h opfile.h stringex.h timex.h pathx.h main.cpp

	g++ -c main.cpp -I /usr/local/include -std=c++11

parsexml.o:tinyxml2.h parsexml.cpp

	g++ -c parsexml.cpp  -std=c++11

tinyxml2.o:

opfile.o:stringex.h timex.h opfile.cpp

	g++ -c opfile.cpp -std=c++11

opmysql.o:opmysql.cpp

	g++ -c opmysql.cpp -I /usr/local/include -std=c++11

stringex.o:stringex.cpp

	g++ -c stringex.cpp -std=c++11

pathx.o:pathx.cpp

	g++ -c pathx.cpp -std=c++11

timex.o:



clean:
	rm $(logtoo_srvd_bin)/logtoo_srvd





原文地址:https://www.cnblogs.com/ggzone/p/10121325.html