如何将程序定义成库函数
程序带main()函数的可以编译成可执行程序,那其他的程序就可以定义成库了。我目前理解层面的库分为两种,一种是静态库以.a作为后缀,一种是共享库以.so后缀。区别在于,编译的时候静态库存在多份,共享库只存在一份。
建立可执行文件helloworld.cpp
#include "libhelloworld.h"
using namespace std;
int main(int argc, char** argv)
{
int u = printf();
return 0;
}
创建库文件的源文件libhelloworld.cpp
#include "libhelloworld.h"
#include <iostream>
using namespace std;
int printf()
{
cout<<"this is a lib"<<endl;
return 0;
}
创建库文件的头文件libhelloworld.h
#ifndef LIB_HELLOWORLD
#define LIB_HELLOWORLD
int printf();
#endif
修改编译规则文件CMakeLists.txt
#声明要求的cmake最低版本
cmake_minimum_required(VERSION 2.8)
#声明一个cmake工程
project(HelloWorld)
#添加一个可执行程序
#语法:add_executable(程序名 源代码文件)
add_executable(helloworld helloSlam.cpp)
#创建库格式,helloworld_share是库文件的名字
#SHARED参数表示创建的是共享库,静态库则不用加中间参数
#libhelloworld.cpp是源文件的名字
add_library(helloworld_share SHARED libhelloworld.cpp)
#给可执行文件链接库
target_link_libraries(helloworld helloworld_share)
执行步骤生成可执行文件和库
cd build
cmake ..
make
执行可执行文件
./helloworld
this is a lib