C 环境设置: gcc
C语言需要编译器编译、链接后才能运行,这个环境一般也统称为编译器。
C语言有多个流行的编译器,如 gcc、clang、llvm、MSVC等,我们这里只介绍 GNU 的 gcc,喜欢其他的也可以自己探索。
Windows 下怎么安装gcc?
最简单的是通过安装 Perl 语言的环境,顺便获得gcc环境。
下载和默认安装: strawberry perl。然后win+R输入cmd打开命令行,输入 gcc --version 即可看到版本号。
C:\Users\wangj>gcc --version gcc (x86_64-posix-seh, Built by strawberryperl.com project) 8.3.0 Copyright (C) 2018 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
CentOS7 无root权限怎么安装最新版gcc?
注:本例使用极简的docker镜像(centos:centos7.9.2009)作为演示环境。
1. 下载
$ cd /home/$USER/Downloads/
$ wget http://ftp.gnu.org/gnu/gcc/gcc-12.1.0/gcc-12.1.0.tar.gz
$ tar zxvf gcc-12.1.0.tar.gz
2. 下载几个依赖
$ cd gcc-12.1.0
$ ./contrib/download_prerequisites #报错
依赖: line 261: bzip2: command not found
$ sudo yum install bzip2
$ ./contrib/download_prerequisites #再执行
gmp-6.2.1.tar.bz2: OK
mpfr-4.1.0.tar.bz2: OK
mpc-1.2.1.tar.gz: OK
isl-0.24.tar.bz2: OK
All prerequisites downloaded successfully.
3. 编译与安装
$ mkdir build
$ cd build
$ ../configure --prefix=/home/$USER/soft/gcc-12.1.0 --enable-shared --enable-threads=posix --enable-languages=c,c++,fortran --disable-multilib
$ make -j 50 #多线程编译,否则巨慢!~几个小时
$ make install
Libraries have been installed in:
/home/wangjl2/soft/gcc-12.1.0/lib/../lib64
If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
- add LIBDIR to the `LD_LIBRARY_PATH' environment variable
during execution
- add LIBDIR to the `LD_RUN_PATH' environment variable
during linking
- use the `-Wl,-rpath -Wl,LIBDIR' linker flag
- have your system administrator add LIBDIR to `/etc/ld.so.conf'
See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
4. 加入环境变量
打开.bashrc
$ vim ~/.bashrc
添加以下三条,需要把路径改成自己的实际路径
export PATH=~/soft/gcc-12.1.0/bin:$PATH
export LD_LIBRARY_PATH=~/soft/gcc-12.1.0/lib:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH=~/soft/gcc-12.1.0/lib64:$LD_LIBRARY_PATH
激活环境
$ source ~/.bashrc
5. 查看版本
$ which gcc
~/soft/gcc-12.1.0/bin/gcc
$ gcc --version
gcc (GCC) 12.1.0 #最新版
Copyright (C) 2022 Free Software Foundation, Inc.
现在系统共2个版本:
$ whereis gcc
gcc: /usr/bin/gcc /usr/lib/gcc /usr/libexec/gcc /data/jinwf/wangjl/soft/gcc-12.1.0/bin/gcc
原来自带的老版本是 gcc 4.8.5
$ /usr/bin/gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
编译并运行
win和linux下的操作类似。
1. 使用文本编辑器编辑代码,保存为.c结尾的文本文件。 $ cat hello.c #includeint main(){ printf("hello, %s\n", "world"); } 2. 使用gcc编译为二进制程序,-o指定输出文件名。 $ gcc hello.c -o hello 3. 执行程序 $ ./hello hello, world