安装C/C++编译环境

操作系统CentOS 5

如果gcc命令不存在,直接用以下命令安装:

yum install gcc

但这默认只安装C语言编译器,如果需要C++编辑器,还需要安装gcc-c++,执行以下命令即可:

yum install gcc-c++

测试编译环境

下面程序来自《Advanced Linux Programming》.

主程序main.c

/**
 * File: main.c
 */
#include <stdio.h>
#include "reciprocal.hpp"

int main(int argc, char** argv)
{
	int i;
	i = atoi (argv[1]);
	printf("The reciprocal of %d is %g\n", i, reciprocal(i));
	return 0;
}

C++程序reciprocal.cpp

/**
 * File: reciprocal.cpp
 */
#include <cassert>
#include "reciprocal.hpp"

double reciprocal (int i) {
	assert(i != 0);
	return 1.0/i;
}

C++头文件reciprocal.hpp

/**
 * File: reciprocal.hpp
 */
#ifdef __cplusplus
extern "C" {
#endif

	extern double reciprocal (int i);

#ifdef __cplusplus
}
#endif

分别执行以下命令:

1. 将main.c编译为目标程序

gcc -c main.c

2. 将reciprocal.cpp编译成目标程序

g++ -c reciprocal.cpp

3. 连接目标程序

g++ -o reciprocal main.o reciprocal.o

4. 运行reciprocal

./reciprocal 2

应该输出:The reciprocal of 2 is 0.5.

完成

About James Tang

Web Developer, focusing on large-scale web application architecture and development.
This entry was posted in Linux, Notes and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


8 - = three

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>