引言
可以在centos7等比较老的linux机器上编译安装部署最新的C++开发环境,以使用c++11/14/17等的新特性。
编译安装gcc
cd /tmpwget https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-8.2.0/gcc-8.2.0.tar.gztar xf gcc-8.2.0.tar.gzcd gcc-8.2.0./contrib/download_prerequisitesmkdir buildcd build../configure --enable-bootstrap --enable-languages=c,c++ --disable-multilib --prefix=/usr/local/c++make -j2make install
编译安装boost
如果有需要可以先安装zlib-devel、bzip2-devel、xz-devel、openmpi-devel、python-devel、libicu-devel开发包
cd /tmpwget https://dl.bintray.com/boostorg/release/1.68.0/source/boost_1_68_0.tar.gztar xf boost_1_68_0.tar.gzcd boost_1_68_0cd tools/build/./bootstrap.sh./b2 install --prefix=/tmp/b2cd ../..echo 'using gcc : 8.2.0 : /usr/local/c++/bin/c++ ;' > project-config.jamecho 'using mpi ;' >> project-config.jam/tmp/b2/bin/b2 --prefix=/usr/local/c++ toolset=gcc variant=release link=static threading=multi install
最后可以strip一下
cd /usr/local/c++find bin lib lib64 libexec -type f -exec strip -g -x {} \;
其它库
对于其它库,如log4cpp、librdkafka,在执行configure时可以通过指定环境变量CC=/usr/local/c++/bin/gcc和CXX=/usr/local/c++/bin/g++来使用上述安装部署的最新环境进行编译,使用--prefix=/usr/local/c++来指定库的安装目录。
使用
由于将开发环境部署在/usr/local/c++目录,对于.so的使用会比较麻烦,无论是拷贝相关so文件还是改LD_LIBRARY_PATH,所以在开发编译自己的程序时推荐使用静态链接的方式。
Makefile
TARGET = ##xxx## ifndef PREFIX PREFIX = /usr/local/$(TARGET) endifCXX_PREFIX = /usr/local/c++INC = -I$(CXX_PREFIX)/includeLIB = $(CXX_PREFIX)/lib/libboost_system.a $(CXX_PREFIX)/lib/liblog4cpp.a $(CXX_PREFIX)/lib/librdkafka.a -lz -lpthread -lcrypto -lrt -ldlCC = $(CXX_PREFIX)/bin/gccCXX = $(CXX_PREFIX)/bin/c++C_FLAGS = -g -O2 -Wall -Wextra -WerrorCXX_FLAGS = $(C_FLAGS) -std=c++14H_FILES = $(shell find src -name "*.h" -type f) $(shell find src -name "*.hpp" -type f)C_FILES = $(shell find src -name "*.c" -type f)C_OBJS = $(subst .c,.o,$(C_FILES))CPP_FILES = $(shell find src -name "*.cpp" -type f)CPP_OBJS = $(subst .cpp,.o,$(CPP_FILES))BASE = $(shell basename $(PWD)).PHONY: all clean install distall: $(TARGET)$(TARGET): $(C_OBJS) $(CPP_OBJS) $(CXX) -o $(TARGET) -static-libgcc -static-libstdc++ $(C_OBJS) $(CPP_OBJS) $(LIB)$(C_OBJS): %.o: %.c $(CC) -c $(C_FLAGS) -o $@ $<$(CPP_OBJS): %.o: %.cpp $(CXX) -c $(CXX_FLAGS) $(INC) -o $@ $