本文为C++程序在不使用IDE情况下,自己组织文件结构的模版;
用g++完成编译和连接过程,make来帮助完成一些自动化过程。
一. 文件结构
文件结构:
文件内容:
见附录。
二. g++与make指令
在同级目录下添加makefile文件,编辑内容如下:
#makefile create main
main:main.o testA.o testB.o testC.o
g++ -o main testA.o testB.o testC.o main.o -lstdc++
testA.o:testA.cpp
g++ -Wall -c testA.cpp -o testA.o
testB.o:testB.cpp
g++ -Wall -c testB.cpp -o testB.o
testC.o:./C_dir/testc.cpp
g++ -Wall -c ./C_dir/testc.cpp -o testC.o
main.o: main.cpp
g++ -Wall -c main.cpp -o main.o
clean:
rm -rf testA.o testB.o testC.o main.o
进入终端,cd到文件目录下,执行make main指令:
> cd ~/Workspace/CppEcample/
> make main
就会在当前目录下生成可执行文件main,以及中间过程产生的*.o文件。如果想统一删除这些.o文件,执行如下指令。
> make clean
附录
各文件内容:
main.cpp:
#include "testA.h"
#include "testB.h"
#include "./c_dir/testC.h"
#include <iostream>
int main(void)
{
classA cA;
classB cB;
classC cC;
cA.set_data(10);
cB.set_data(20);
cB.set_data(30);
cA.show_data();
cB.show_data();
cC.show_data();
return 0;
}
testA.h:
#ifndef _testA_h_
#define _testA_h_
#include <iostream>
class classA
{
private:
int dataA;
public:
void set_data(int data);
void show_data(void);
};
#endif
testA.cpp:
#include "testA.h"
void classA:: set_data(int data)
{
dataA=data;
}
void classA:: show_data(void)
{
std::cout<<"data of classA is"<<dataA<<std::endl;
}
testB.h:
#ifndef _testB_h_
#define _testB_h_
#include <iostream>
class classB
{
private:
int dataB;
public:
void set_data(int data);
void show_data(void);
};
#endif
testB.cpp
#include "testB.h"
void classB:: set_data(int data)
{
dataB=data;
}
void classB:: show_data(void)
{
std::cout<<"data of classB is"<<dataB<<std::endl;
}
C_dir/testC.h
#ifndef _testC_h_
#define _testC_h_
#include <iostream>
class classC
{
private:
int dataC;
public:
void set_data(int data);
void show_data(void);
};
#endif
C_dir.testC.cpp:
#include "testC.h"
void classC:: set_data(int data)
{
dataC=data;
}
void classC:: show_data(void)
{
std::cout<<"data of classC is"<<dataC<<std::endl;
}