Skip to content Skip to main navigation Skip to footer

Linux:如何在linux下编译/运行C/C++程序

对于一个linux新手来说,可能想知道如何才能在linux编译并执行自己写的C/C++语言程序?为了在各种不同的linux系统(redhat,ubuntu,fedora,debian)下编译C或者C++程序,还需要安装一些必要的包:
1. GNU C 和C++编译器
2.开发工具包
3. 开发库
4. 编辑器软件包
第一步,安装C/C++编译器
对于Redhat发布的几个linux发布版本,可以使用下面的命令安装GNU c/C++编译器:

[root@devops ~]# yum groupinstall 'Development Tools'
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.btte.net
* extras: mirrors.btte.net
* updates: mirrors.btte.net
base                                                                         | 3.7 kB     00:00
extras                                                                       | 3.4 kB     00:00
updates                                                                      | 3.4 kB     00:00
updates/primary_db                                                           | 2.6 MB     00:00
Setting up Group Process
Checking for new repos for mirrors
base/group_gz                                                                | 220 kB     00:00
Package gcc-4.4.7-4.el6.x86_64 already installed and latest version
Package 1:pkgconfig-0.23-9.1.el6.x86_64 already installed and latest version
Resolving Dependencies
--> Running transaction check
---> Package autoconf.noarch 0:2.63-5.1.el6 will be installed
---> Package automake.noarch 0:1.11.1-4.el6 will be installed
---> Package binutils.x86_64 0:2.20.51.0.2-5.34.el6 will be updated
...
 

对于ubuntu的系统,可以使用下面的命令来安装c/C++编译器

[root@devops ~]#sudo apt-get update
[root@devops ~]#sudo apt-get install build-essential manpages-dev
 

安装完之后,我们可以验证下是否安装成功

[root@devops ~]# gcc --version
gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-4)
Copyright ? 2010 Free Software Foundation, Inc.
[root@devops ~]# whereis gcc
gcc: /usr/bin/gcc /usr/lib/gcc /usr/libexec/gcc /usr/share/man/man1/gcc.1.gz
[root@devops ~]#
 

下面来举个例子,编译并执行C/C++程序:

#include ;
int main(void) {
printf ("hello Wolrd!\n");
}

那么如何在linux下编译/运行C语言程序呢?
我们可以使用下面的命令cc或者gcc来编译c语言程序:

[root@devops ~]# gcc test.c -o test
[root@devops ~]# ./test
hello Wolrd!
[root@devops ~]#
 

如何在linux下编译/运行C++程序呢?

#include "iostream"
int main(void) {
std::cout << "hello world.\n";
}

使用g++命令编译c++程序:

[root@devops ~]# g++ test.C -o test
 

运行编译之后的可执行程序:

[root@devops ~]# ./test
hello world.
[root@devops ~]#
 
0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.