大家都知道,linux下編寫C++需要寫make檔案,小程式則好些多了,但是龐大的工程,直接用手寫就不好了,下面樣本:
1.測試小程式
demo1
---------main.cpp
---------hello.h
---------hello.cpp
#main.cpp
#include "hello.h"<br />int main()<br />{<br /> PrintHello();<br /> return 0;<br />}
#hello.h
#ifndef __HELLO_H__<br />#define __HELLO_H__<br />void PrintHello();<br />#endif
#hello.cpp
#include <stdio.h><br />#include "hello.h"<br />void PrintHello()<br />{<br /> printf("%s/n", "Hello,World!");<br /> return;<br />}<br />
2.手動編寫makefile
touch一個makefile檔案,在demo1目錄下
#makefile
hello:hello.o main.o<br /> g++ hello.o main.o -o hello<br /> rm hello.o main.o</p><p>hello.o: hello.h hello.cpp<br /> g++ -c hello.cpp -o hello.o<br />main.o:hello.h main.cpp<br /> g++ -c main.cpp -o main.o
執行命令
make
./hello
看到運行結果了。
3.使用automake和autoscanf工具自動產生Makefile檔案
3.1在demo1目下
執行autoscan,將產生的configure.scan重新命名為configure.in
且修改
#修改前
# -*- Autoconf -*-<br /># Process this file with autoconf to produce a configure script.<br />AC_PREREQ(2.61)<br />AC_INIT(FULL-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS)<br />AC_CONFIG_SRCDIR([hello.cpp])<br />AC_CONFIG_HEADER([config.h])<br /># Checks for programs.<br />AC_PROG_CXX<br />AC_PROG_CC<br /># Checks for libraries.<br /># Checks for header files.<br /># Checks for typedefs, structures, and compiler characteristics.<br /># Checks for library functions.<br />AC_CONFIG_FILES([Makefile])<br />AC_OUTPUT<br />
#修改後,注意對比
# -*- Autoconf -*-<br /># Process this file with autoconf to produce a configure script.<br />AC_PREREQ(2.61)<br />AC_INIT(testhello, 0.1, idehong@gmail.com)<br />AM_INIT_AUTOMAKE(testhello, 0.1)<br />AC_CONFIG_SRCDIR([hello.cpp])<br />AC_CONFIG_HEADER([config.h])<br /># Checks for programs.<br />AC_PROG_CXX<br />AC_PROG_CC<br /># Checks for libraries.<br /># Checks for header files.<br /># Checks for typedefs, structures, and compiler characteristics.<br /># Checks for library functions.<br />AC_CONFIG_FILES([Makefile])<br />AC_OUTPUT<br />
3.2
執行命令
aclocal
會產生aclocal.m4檔案,給後面命令用
autoconf
此時會產生config.in檔案
建立Makefile.am,每個目錄都需要建立Makefile.am檔案
#Makefile.am
AUTOMAKE_OPTIONS=foreign<br />bin_PROGRAMS = demo1<br />demo1_SOURCES=main.cpp hello.cpp hello.h<br />
注意,根資料夾下的Makefile.am檔案中需要帶AUTOMAKE_OPTIONS=foreign
執行命令
autoheader
產生config.h.in檔案
automake --add-missing
3.3終於看到configure檔案了
執行命令
./configure
make
產生demo1檔案了
3.4
執行命令
./demo1
看到運行結果了
Hello,World!
小工程手工編寫Makefile蠻簡單,工程複雜了就困難了,還要考慮依賴關係,不如把這些麻煩的事情交給autoscan和automake吧,他們更勝於做這些事情。