我正在使用gcc(cygwin),gnu make,Windows 7和cmake。

我的cmake testprojekt具有以下结构

rootdir
|-- App
|   |-- app.cpp
|   +-- CMakeLists.txt
|-- Lib
|   |-- lib.cpp
|   |-- CMakeLists.txt
|-- MakeFileProject
+ CMakeLists.txt

rootdir/App/app.cpp:

#include<string>
void printThemMessageToScreen(std::string input);//prototype
int main(int argc,char **argv){
 printThemMessageToScreen("this will be displayed by our lib");
 return 0;
}

rootdir/Lib/lib.cpp:

#include<iostream>
#include<string>

void printThemMessageToScreen(std::string input){
 std::cout<<input;
}

rootdir/CMakeLists.txt:
cmake_minimum_required(VERSION 2.6)
project(TestProject)

add_subdirectory(App)
add_subdirectory(Lib)

rootdir/Lib/CMakeLists.txt:
add_library(Lib SHARED lib.cpp)

rootdir/App/CMakeLists.txt:
# Make sure the compiler can find include files from our Lib library.
include_directories (${LIB_SOURCE_DIR}/Lib)

# Make sure the linker can find the Lib library once it is built.
link_directories (${LIB_BINARY_DIR}/Lib)

# Add executable called "TestProjectExecutable" that is built from the source files
add_executable (TestProjectExecutable app.cpp)

# Link the executable to the lib library.
target_link_libraries (TestProjectExecutable Lib)

现在,当我运行cmake和make时,所有内容都会生成且没有错误生成,但是当我尝试执行二进制文件时,它将失败,因为找不到生成的库。

但是:当我将lib dll复制到与应用exe相同的目录中时,它将被执行!

还:如果我将库配置为静态,它也会执行。

如何告诉运行时链接程序在哪里寻找我的dll?

更新:

根据用户Vorren提出的方法的解决方案:

我打开了注册表编辑器,并导航到以下项:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths

,在这里我创建了一个名为Applikation的新 key :

在这种情况下:TestProjectExecutable.exe

之后,(默认)值将设置为TestProjectExecutable.exe的完整路径,包括文件名和扩展名。然后,我创建了另一个名为“Path”的字符串值,并将该值设置为dll所在的文件夹:

最佳答案

您的问题不在于链接器或编译器,而在于Windows搜索DLL的方式。

操作系统将使用以下算法来查找所需的DLL:

在看:

  • 特定于应用程序的路径注册表项中列出的目录;
  • 当前进程的可执行模块所在的目录。
  • 当前目录;
  • Windows系统目录;
  • Windows目录;
  • PATH环境变量中列出的目录;

  • 因此,如果您不想使用特定于应用程序的dll来打乱OS目录,则有两个合理的选择:
  • 创建特定于应用程序的Path注册表项(我会使用此选项)
  • 将DLL与EXE放在同一文件夹中;
  • 修改PATH变量(但是,如果可以使用选项1,为什么要这么做呢?)
  • 关于c++ - 使用cmake构建可执行文件和共享库,runtimelinker找不到dll,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23323741/

    10-14 15:48
    查看更多