C/C++ programming for linux

C/C++ programming for linux

1. Pre-Processing

g++ -E test.cpp -o test.i    //.i文件
# -E 指示编译器仅对出入文件进行预处理

2. Compiling Compiling

g++ -S test.i -o test.s
# -S 编译器选项告诉g++在为C++代码产生了汇编语言文件后停止编译
# g++ 产生的汇编文件的缺省扩展名 .s

3. Assembly Assembling

g++ -c test.s -o test.o

4 Linking

g++ test.o -o test

Important parameters in g++

-g 编译带调试信息的可执行文件,这个选项会产生能被gdb使用的调试信息
-O[n] 优化源代码 
-l 和 -L 指定库文件 | 指定库文件路径
g++ -lglog test.cpp  #链接的是glog库
-l 所指定的库在/lib或 /usr/lib 或 /usr/local/lib
-L 要自己表明所使用的库在哪里
g++ -L/home/bing/mytestlibfolder -lmytest test.cpp
-I 指定头文件搜索目录
g++ 默认搜索的头文件路径在/usr/include中
g++ -I/myinclude test.cpp  #这里用的是绝对路径
-Wall 打印警告信息
-w 关闭警告信息
-std=c++11 设置编译标准
-o 指定输出文件名
-D 定义宏
g++ -DDEBUG main.cpp
#incldue <stdio.h>
int main(){
    
    
	#ifdef DEBUG
		printf("DEBUG LOG\n");
	#endif
		printf("in\n");
}

Original compilation and execution

g++ main.cpp src/swap.cpp -Iinclude

Generate a library file

folder path

--include
	--swap.h
--main.cpp
--src
	--swap.cpp
#进入src目录
$cd src
#汇编 生成Swap.o二进制文件
g++ Swap.cpp -c -I../include -o Swap.o

#生成静态库libSwap.a  ar是归档命令,把二进制文件归档为一个静态库
ar rs libSwap.a Swap.o

#回到上级目录
$cd ..

#链接这个静态库libSwap.a,生成可执行文件:staticmain
g++ main.cpp -Iinclude -Lsrc -lSwap -o staticmain
#这个-lSwap 有点怪 生成的库文件名为libSwap.a 引用的时候直接写Swap 即 -lSwap就行了

After generating the library file, you don’t need to type out the full name of the referenced source cpp file when referencing it. You only need to specify the library function folder, and it will be actively searched when compiling the program.

#生成动态库libSwap.so
g++ Swap.cpp -I../include -fPIC -shared -o libSwap.so
#链接动态库libSwap.so
g++ main.cpp -Iinclude -Lsrc -lSwap -o sharemain
#但是的执行的时候首先指定系统搜索动态库的路径
LD_LIBRARY_PATH=src ./sharemain

Guess you like

Origin blog.csdn.net/xuanyitwo/article/details/129741483