附上工程源码
库文件工程
PS:这个工程用于导出库
CMakeLists.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| cmake_minimum_required(VERSION 3.5)
project(demo LANGUAGES CXX)
set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_library(demo SHARED demo.cpp demo.h )
target_compile_definitions(demo PRIVATE DEMO_LIBRARY)
|
demo.h
1 2 3 4 5 6 7 8 9 10 11 12
| #ifndef DEMO_H #define DEMO_H
class Demo { public: Demo();
void Print(); };
#endif
|
demo.cpp
1 2 3 4 5 6 7 8 9 10 11
| #include "demo.h" #include <iostream>
Demo::Demo() { }
void Demo::Print() { std::cout << "this is a demo" << std::endl; }
|
主程序工程
PS:这个工程用于链接demo库
CMakeLists.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| cmake_minimum_required(VERSION 3.5)
project(find-library LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON)
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/inc)
find_library(LIB_DEMO demo ${CMAKE_CURRENT_SOURCE_DIR}/lib)
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} ${LIB_DEMO})
|
main.cpp
1 2 3 4 5 6 7 8 9 10 11
| #include <iostream> #include "demo.h"
using namespace std;
int main() { Demo d; d.Print(); return 0; }
|
问题情形
首先这两个工程在Linux下使用没有问题的,find-library工程编译正常,可以正确链接demo库;但是在Windows平台就死活不行了,find-library工程CMakeLists.txt第10行老是报错提示demo库找不到
1 2
| LIB_DEMO linked by target "find-library" in directory E:/workspace/daily-project/cpp/find-library
|
但明明是把demo工程生成的库拷贝到find-library工程的lib目录下了,为啥就是死活会报错?Windows难道对库文件的格式有要求?
解决办法
尝试把demo工程的CMakeLists.txt第9行SHARED
改成STATIC
,重新编译demo,再把生成的静态库文件demo.lib
拷贝到find-library工程的lib目录下,重新编译该工程却出乎意料的成功了!但参考官网find_library的用法却没有得到解析
总结
下次写跨平台编译的代码的时候记得在cmake上面配置生成不同类型的库(Windows平台生成两种库准没错)