首页 > 解决方案 > How to deal with dependencies when cross-compiling

问题描述

Having transferred a research project into a startup, I suddenly need to distribute binaries rather than source code + build instructions. I have a C++ codebase built using CMake.

I find myself completely out of my depth here, to the point where I can't seem to find the resources I need to get started. The problem more specifically is how to cross-compile source code in such a way that users can load dependent libraries from wherever they have them installed (also grateful for pros/cons of dynamic/static libraries in these circumstances). Right now, when I build my targets, the binaries automatically link to paths specific to my host environment which of course isn't workable for distributing the binaries. I am looking for:

  1. A high level description of how this could be done using CMake,
  2. Some pointers to resources that are accessible enough for a complete cross-compiling noob to understand.

Edit: I realized I actually have two questions rather than one. One of them was about cross-compiling, and I am satisfied with actually using machines (real or virtual) with different OS to build for each OS, eliminating the need to cross-compile between e.g. Windows and Mac. The other question, which I still don't know how to deal with, is how to build the executable on my machine and distributing it to other machines with the same OS given that the executable uses dynamically linked dependencies which will very likely be installed at different paths, or be of different versions on users' machines. How do I build a binary on my machine, that (possibly with the help of cmake's find_package or something similar) can be linked to the dependencies wherever the user has them installed on their system, without needing to share the source code?

标签: c++cmakecross-compilinglibraries

解决方案


从我的角度来看,使用 cmake 导入库项目就可以了。

cmake_minimum_required(VERSION 3.0)

project(specific_library)

if(WINDOWS)
    set(imported_lib ${win_lib})
elseif(LINUX)
    set(imported_lib ${linux_lib})
elseif(ANDROID)
    set(imported_lib ${android_lib})
endif(WINDOWS)

add_library(
    ${PROJECT_NAME}
    STATIC
    IMPORTED
    GLOBAL
)

在主项目目录中,你可以这样做

add_subdirectory(specific_library)
target_link_libraries(
    ${PROJECT_NAME}
    PUBLIC
    specific_library
)

推荐阅读