如何使用CMake正确链接外部库?

时间:2017-03-29 06:32:00

标签: c++ cmake cryptography rsa chilkat

我正在尝试使用Chilkat C ++库进行加密分配,但我似乎无法让库正确链接。截至目前,编译器无法找到头文件CkRsa.h。我花了几个小时在互联网上搜索无效的解决方案。这是我到目前为止(这是在Mac OS X环境中):

lib文件安装在/ users / Adam / Desktop / chilkat / libDyn中,头文件位于/ users / Adam / Desktop / chilkat / include中 这是我的CMakeLists.txt

cmake_minimum_required(VERSION 3.6)
project(SocketEncryption)

set(CMAKE_CXX_STANDARD 11)

set(SOURCE_FILES main.cpp)

add_library(chilkat STATIC IMPORTED)
set_property(
        TARGET chilkat
        PROPERTY
        IMPORTED_LOCATION "/users/Adam/Desktop/chilkat/libDyn/libchilkat_x86_64.dylib"
        INTERFACE_INCLUDE_DIRECTORIES "/users/Adam/Desktop/chilkat/include"
)
add_executable(SocketEncryption ${SOURCE_FILES})

target_link_libraries(SocketEncryption chilkat)

这是我的main.cpp

#include <iostream>
#include <CkRsa.h>
//#include <CkPrivateKey.h>
//#include <CkSocket.h>

int main() {
    CkRsa alice;
    CkRsa bob;

    // Key Generation
    bool success = alice.GenerateKey(1024);
    const char *alicePublicKey = alice.exportPublicKey();
    const char *alicePrivateKey = alice.exportPrivateKey();
    const char *aliceMessage = "Hi, Bob. How are you?";

    // Encryption Step
    std::cout << "Encryption started." << std::endl;
    CkRsa rsaEncryptor;
    rsaEncryptor.put_EncodingMode("hex");
    success = rsaEncryptor.ImportPublicKey(alicePublicKey);
    bool usePrivateKey = false;
    const char * ciphertext = rsaEncryptor.encryptStringENC(aliceMessage, success);
    std::cout << ciphertext << std::endl;


    return 0;
}

2 个答案:

答案 0 :(得分:0)

像这样(引用)更改您的代码:

include_directories("/users/Adam/Desktop/chilkat/include")
link_directories("/users/Adam/Desktop/chilkat/libDyn")

答案 1 :(得分:0)

我认为这是您订购电话的一个简单问题。 CMake确实按顺序解析其脚本。因此include_directories()调用必须在add_executable()调用之前发出:

include_directories("/users/Adam/Desktop/chilkat/include")
add_executable(SocketEncryption ${SOURCE_FILES})

自CMake 2.8.12以来更好的方法是让库传播其头文件路径:

target_include_directories(chilkat PUBLIC "/users/Adam/Desktop/chilkat/include")

或 - 为了便于阅读 - 直接通过目标属性添加:

set_property(
    TARGET chilkat 
    PROPERTY 
        IMPORTED_LOCATION "/users/Adam/Desktop/chilkat/libDyn/libchilkat_x86_64.dylib"
        INTERFACE_INCLUDE_DIRECTORIES "/users/Adam/Desktop/chilkat/include"
)

另见CMake: Creating Relocatable Packages

<强>参考