linux下编译C++工程入门

COPY FROM:http://blog.163.com/seraph_leo/blog/static/16892971020107863258272/

熟悉了Windows平台下编译一个C++工程后,你是否会提出这样一个问题:在Linux平台下又如何编译一个C++工程呢?

希望本文能给正在学习或想学习Linux C++开发的你起到抛砖引玉的作用。

首先,你必须有一个Linux开发环境,这样才能进行C++开发。笔者用的是安装在虚拟机中的Redhat Linux Enterprise 5.0,所以不用担心操作系统没带C++编译器g++。如果您使用的Ubuntu,是没有自带C++编译器,可在连网的情况下,在终端中使用root超级用户权限输入以下命令:sudo apt-get install g++并回车即可安装C++编译器g++。

安装完毕,即可开始新建我们的一个C++工程了。下面以一个hello工程为例,简单地介绍如何编译一个 C++工程。

登录Linux系统,打开终端,在当前目录下使用mkdir命令新建一个hello的目录;然后使用cd hello进入hello目录中,并使用vi工具新建hello.h、hello.cpp、main.cpp、makefile四个文件。四个文件的内容分别如下:1. hello.h文件/** hello.h** Created on: 2009-6-27* Author: young*/#ifndef HELLO_H_#define HELLO_H_class Hello {public:void print();};#endif /* HELLO_H_ */

2. hello.cpp文件#include "hello.h"#include <iostream>using namespace std;void Hello::print() {cout<<"Hello, welcome to Redhat Linux os!"<<endl;}

3. main.cpp文件#include "hello.h"#include <iostream>using namespace std;int main() {Hello h;h.print();return 0;}注意:这三个文件要以空白行结束,否则编译时会有警告信息。

4. makefile文件# this is a makefile of the c++ project hello# the standard c++ compiler in the Redhat linux is g++# written by young on June 27th, 2009TARGET = .CC = g++CFLAGS = -gCFLAGC = -cMAINC = main.cppHELLO = hello.cppOBJ = hello.oINCLUDE = -I$(TARGET)EXEC = $(TARGET)/mainall: $(EXEC)$(EXEC): $(OBJ) $(MAINC)$(CC) $(CFLAGS) $(OBJ) $(MAINC) $(INCLUDE) -o $@if [ -f *.o ]; then rm -f *.o; fi@echo "<<<<<< $@ is created successfully! >>>>>>"$(OBJ): $(HELLO)$(CC) $(CFLAGC) $(HELLO) -o $@clean:rm -f $(EXEC)

此外,makefile文件还能写成如下格式:

# this is a makefile of the c++ project hello# the standard c++ compiler in the Redhat linux is g++# written by young on June 27th, 2009TARGET = .CC = g++CFLAGS = -gCFLAGC = -cMAINC = main.cppHELLO = hello.cppINCLUDE = -I$(TARGET)EXEC = $(TARGET)/mainall: $(EXEC)

$(EXEC): $(MAINC) $(HELLO)$(CC) $(CFLAGS) $(MAINC) $(HELLO) $(INCLUDE) -o $@@echo "<<<<<< $@ is created successfully! >>>>>>"clean:rm -f $(EXEC)注意: makefile文件中的命令行(红色字体)一定要以Tab键开头,否则编译通不过。

写好makefile文件后,即可编译工程。在终端中输入make命令,回车后将显示如下信息:g++ -c hello.cpp -o hello.og++ -g hello.o main.cpp -I. -o mainrm -f hello.o<<<<<< main is created successfully! >>>>>>

这些信息说明工程已被正确编译,当前目录下将生成一个main的可执行文件。

同样,你也可以不使用makefile文件,而直接在终端上输入以下两行命令:g++ -c hello.cpp -o hello.og++ -g hello.o main.cpp -I. -o main也可以编译这个工程。

使用ls -l命令查看当前目录下的所有文件,确实有一个main文件。在终端中输入./main,即可运行程序。

饶人不是痴汉,痴汉不会饶人。

linux下编译C++工程入门

相关文章:

你感兴趣的文章:

标签云: