首页 > 解决方案 > 在 Docker/CMake 项目中包含外部库

问题描述

我正在使用 docker 和 cmake 构建一个 cxx 项目,我现在的任务是集成我在本地拥有的第三方库。

首先,我添加了一个项目,该项目仅包含一个 src 文件夹和一个具有 main 功能的 cpp 文件,以及我需要从上述库中获得的内容。此时,我已经陷入困境,因为在 docker 环境中构建时找不到包含的文件。当我在项目上调用没有 docker 的 cmake 时,我没有收到包含错误。

我的目录树:

my_new_project
    CMakeLists.txt
    src
        my_new_project.cpp

CMakeLists.txt我有以下内容:

CMAKE_MINIMUM_REQUIRED (VERSION 3.6)

project(my_new_project CXX)
file(GLOB SRC_FILES src/*.cpp)
add_executable(${PROJECT_NAME} ${SRC_FILES})

include_directories(/home/me/third_party_lib/include)

在 Docker 环境中进行此构建需要什么?我是否需要将第三方库转换为另一个项目并将其添加为依赖项(类似于我对来自 GitHub 的项目所做的操作)?

我会很高兴有任何指向正确方向的指示!

编辑

我已经复制了整个第三方项目的根目录,现在可以使用 来添加包含目录include_directories(/work/third_party_lib/include),但这会是要走的路吗?

标签: dockercmake

解决方案


当您构建一个新的 dockerized 应用程序时,您需要COPY/ADD所有 src、build 和 cmake 文件,并RUNDockerfile. 这将用于构建您的 docker image,以捕获所有必要的二进制文件、资源、依赖项等。一旦构建了映像,您就可以从 docker 上的该映像运行容器,它可以公开端口、绑定卷、设备等为您的应用程序。

所以本质上,创建你的Dockerfile

# Get the GCC preinstalled image from Docker Hub
FROM gcc:4.9

# Copy the source files under /usr/src
COPY ./src/my_new_project /usr/src/my_new_project

# Copy any other extra libraries or dependencies from your machine into the image
COPY /home/me/third_party_lib/include /src/third_party_lib/include

# Specify the working directory in the image
WORKDIR /usr/src/

# Run your cmake instruction you would run
RUN cmake -DKRISLIBRARY_INCLUDE_DIR=/usr/src/third_party_lib/include -DKRISLIBRARY_LIBRARY=/usr/src/third_party_lib/include ./ && \
make && \
make install

# OR Use GCC to compile the my_new_project source file
# RUN g++ -o my_new_project my_new_project.cpp

# Run the program output from the previous step
CMD ["./my_new_project"]

然后你可以做一个docker build . -t my_new_project然后docker run my_new_project尝试一下。

Also there are few great examples on building C** apps as docker containers:

For more info on the this, please refer to the docker docs:


推荐阅读