小菜鸡记录g++的编译链接使用过程

234 阅读1分钟

g++/gcc的常用编译参数

-o:表示进行输出

-c:表明进行的是编译阶段

-L(大写的L):指定链接库所在的文件夹,比如:-Lusr/lib

-l(小写的l):需要用到的链接库的库名,比如有个链接库libMyTest.a,则-lMy_Test

-I(大写的i):指定头文件的搜索路径

使用例子

现在有一个头文件,三个cpp文件定义头文件中的函数,一个main函数

SoDemoTest.h

#ifndef _SO_DEMO_TEST_HEADER_  
#define _SO_DEMO_TEST_HEADER_  
#include <iostream>  
using namespace std;  
void one();  
void two();  
void three();  
#endif

one.cpp

/* one.cpp */  
#include "SoDemoTest.h"  
void one(){  
    cout << "call one() function" << endl;  
}

two.cpp

/* two.cpp */  
#include "SoDemoTest.h"  
void two(){  
    cout << "call two() function" << endl;  
}

three.cpp

/* three.cpp */  
#include "SoDemoTest.h"  
void three(){  
    cout << "call three() function" << endl;  
}

main.cpp

/* main.cpp */  
#include "SoDemoTest.h"  
int main(){  
    one();  
    two();  
    three();  
    return 0;  
}
  • 分别编译每个cpp文件
[devotedliu@security-dev /home/devotedliu/MyWork/test_g++]$g++ -c main.cpp
[devotedliu@security-dev /home/devotedliu/MyWork/test_g++]$g++ -c one.cpp 
[devotedliu@security-dev /home/devotedliu/MyWork/test_g++]$g++ -c two.cpp 
[devotedliu@security-dev /home/devotedliu/MyWork/test_g++]$g++ -c three.cpp
  • 生成静态链接库,注意链接库的命名要以lib开头
[devotedliu@security-dev /home/devotedliu/MyWork/test_g++]$ar cqs libstaticlib.a one.o two.o three.o
  • 使用生成的链接库进行链接
[devotedliu@security-dev /home/devotedliu/MyWork/test_g++]$g++ -o static_main main.o -L. -lstaticlib
  • 运行可执行文件
[devotedliu@security-dev /home/devotedliu/MyWork/test_g++]$./static_main
call one() function
call two() function
call three() function