生成库文件

在项目开发过程中,有时我们不想将我们的某些功能如何实现暴露出来,我们可以只提供声明的头文件+对应的库文件来实现,下面介绍一下如何生成库文件以及如何使用。

创建项目

  • 创建一个glibrary的文件夹
  • 在该文件夹下创建如下几个文件CMakeLists.txt、build、include、src、use_library.cpp
  • 在inlude目录下创建一个test.h文件,其代码如下
#ifndef _TEST_H
#define _TEST_H

namespace Test {
    void test();
}


#endif
  • 在src目录下创建一个test.cpp文件,其代码如下
#include "include/test.h"
#include 

namespace Test {
    void test()
    {
        std::cout << "hello" << std::endl;
    }
}

  • use_library.cpp其代码如下
#include "include/test.h"
using namespace Test;

int main()
{
    test();
    return 0;
}

CMakeLists.txt定义

cmake_minimum_required(VERSION 2.8)
add_definitions(-std=c++11)
project(self_library)

set(TEST_SRC
    src/test.cpp)

include_directories(.)

# use SHARED mode as dynamic link
add_library(hello_library SHARED ${TEST_SRC})

add_executable(use_library use_library.cpp)
target_link_libraries(use_library hello_library)

完成上述所有操作之后,进入到build目录执行如下:

cmake .. && make -j8

在其文件夹下生成libhello_library.dylib和use_library。

./use_library 

如果输出hello则表示操作无误,其库生成正确。
总体来说大概步骤就这么多,有一些细节部分如有需求可以在CMakeLists.txt进行添加。

你可能感兴趣的:(C++)