C ++将两个共享库链接到main.cpp

时间:2017-03-01 12:24:38

标签: opencv c++11 makefile cmake shared-libraries

我遇到一些问题尝试将两个共享库链接到cmake文件中的main.cpp文件。

我的文件夹树是:

**mainfolder**
    |_main.cpp
    |_CMakeLists.txt
    |
    | **lib**
         |_**lib1**
              |_CMakeLists.txt
              |_liblib1.so
              |_**src**
                   |_lib1.cpp
              |_**include**
                   |_lib1.h
         |_**lib2**
              |_CMakeLists.txt
              |_liblib2.so
              |_**src**
                   |_lib2.cpp
              |_**include**
                   |_lib2.h

两个库的两个CMakeLists.txt非常相似,并根据this link创建:

cmake_minimum_required(VERSION 2.6)
project( LibraryLib1 C CXX )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall")
set(CMAKE_BUILD_TYPE Release)
find_package( OpenCV REQUIRED )
# Find source files
file(GLOB SOURCES src/*.cpp)
# Include header files
include_directories(include)
# Create shared library
add_library(${PROJECT_NAME} SHARED ${SOURCES})
# Install library
install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME})
# Install library headers
file(GLOB HEADERS include/*.h)
install(FILES ${HEADERS} DESTINATION include/${PROJECT_NAME})

我的main.cpp文件是:

#include <stdio.h>
#include <stdlib.h>
#include <opencv2/opencv.hpp>
#include "lib/lib1/lib1.h"
#include "lib/lib2/lib2.h"

using namespace cv;

int main()
{
    printf("Executing main.cpp");

    lib1 lib1object;
    lib2 lib2object;

    for(;;)
    {

         lib1object.Analize(param1, param2);
         lib2object.Draw(param1, param2, param3);
    }
    return 0;
}

我的main.cpp应该调用openCV +两个库。你能否告诉我在主文件夹中添加到CMakeLists.txt的哪一行来运行我的主?

此时主文件夹/ CMakeLists.txt是:

cmake_minimum_required(VERSION 2.8)
project( MyProject C CXX )
find_package( OpenCV REQUIRED )
add_executable( main main.cpp )
target_link_libraries( main ${OpenCV_LIBS})

我非常感谢你的帮助。谢谢!

还有一件事......如果我将主文件夹/ CMakeLists.txt的最后一行修改为:

target_link_libraries( main ${OpenCV_LIBS} LibraryLib1 LibraryLib2)

其中LibraryLib1和LibraryLib2是两个库项目的名称,我得到:

/usr/bin/ld: unable to find -lLibraryLib1
/usr/bin/ld: unable to find -lLibraryLib2

1 个答案:

答案 0 :(得分:1)

您有库和主文件的单独项目。因此,主文件不知道其他项目的目标名称。最简单的解决方案(因为所有内容都在一个源代码树中)只有一个项目。

因此,使用add_subdirectory直接在主项目中构建您的libarires:

cmake_minimum_required(VERSION 2.8)
project( MyProject C CXX )
add_subidrectory(lib/lib1)
add_subidrectory(lib/lib2)
find_package( OpenCV REQUIRED )
add_executable( main main.cpp )
target_link_libraries( main ${OpenCV_LIBS} LibraryLib1 LibraryLib2)

这可确保目标名称已知。这假定您在add_library(LibraryLib1...等子文件夹中进行了调用。否则,请适当地交换名称。