c++ - CMake Unresolved external 问题

标签 c++ visual-studio-2013 cmake linker-errors

我正在尝试使用 Visual Studio 2013 编译一个非常简单的 CMake 项目,但是在尝试编译它时出现以下错误:

error LNK1120: 1 unresolved externals   cmake_issue\build\Debug\cmake_issue.exe 1   1   cmake_issue
error LNK2001: unresolved external symbol "public: static int Other::value" (?value@Other@@2HA) cmake_issue\build\test.obj  cmake_issue

我有一个基本目录,其中包含以下CMakeLists.txt:

project(cmake_issue)
add_subdirectory(other)
add_executable(cmake_issue src/test.cc)
target_link_libraries(cmake_issue other)

以及src/test.cc的内容:

#include <cstdio>

#include "other/other.h"

int main(int argc, char *argv[]) {
    printf("value = %d\n", Other::value);

    return 0;
}

还有一个名为 other 的子目录,其中包含以下 CMakeLists.txt:

add_library(other SHARED src/other.cc)
target_include_directories(other PUBLIC include)
target_link_libraries(other)

以及other/include/other/other.h的内容:

#ifndef _OTHER_H_
#define _OTHER_H_

class __declspec(dllexport) Other {
public:
    static int value;
};

#endif

以及other/src/other.cc的内容:

#include "other/other.h"

int Other::value = 30;

如果我使用 cmake 构建项目,然后在 Visual Studio 中打开生成的 sln,这两个项目都会出现在解决方案资源管理器中。

如果我右键单击并构建other,它构建得很好。但是,如果我尝试构建 cmake_issue,我会收到上述错误。看起来cmake_issue解决方案没有使用编译other时生成的other.dll(或other.lib)文件 解决方案。

如果需要,我可以上传源代码的 zip 文件。

最佳答案

好吧,问题不在于 CMake 方面,而在于 C++ 方面。当您在可执行文件中使用 dllexport'ed 类时,其定义应为 class __declspec(dllimport) Other。此代码运行良好,例如:

#include <cstdio>

class __declspec(dllimport) Other {
public:
    static int value;
    int a();
};

int main(int argc, char *argv[]) {
    printf("value = %d\n", Other::value);

    return 0;
}

这是完整解决方案的链接:https://social.msdn.microsoft.com/Forums/en-US/6c43599d-6d9d-4709-abf5-4d1e3f5e4fc9/exporting-static-class-members

关于c++ - CMake Unresolved external 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32108071/

相关文章:

Qt/CMake 难以处理新的源文件

variables - 将来自 .cmake 文件的源变量包含到 CMakeList.txt 的正确方法

c++ - 类方法作为函数参数

c# - 有没有办法在 Visual Studio 2010 中突出显示当前事件的代码块?

c++ - 编译代码太快会出错

c# - VS 2013 Professional Update 4 中无法再打开 .cs 文件

c# - 重写抽象方法的 System.AccessViolationException

c++ - 为外部项目设置 RPATH?

用于检查字符串是否平衡 ()、{} 和 [] 的 C++ 程序

c++ - RapidXML 属性值错误