gpt4 book ai didi

c++ - Windows C++ 静态库在初始化期间无法访问外部方法

转载 作者:行者123 更新时间:2023-11-30 03:13:19 25 4
gpt4 key购买 nike

我正在将大型 Windows C++ 应用程序从大量源文件转换为一个较小的核心应用程序链接到几个静态库(许多的原始源文件被移动)。

每个库都需要访问核心应用程序中的“注册方法”。每个库都应该在全局初始化期间调用该方法,但那是没有发生。那是我的问题。

代码在未使用库的原始形式下运行良好。我想我省略了库的必要链接选项,但是我不知道是哪个。

我创建了一个最小的、可行的示例。我开发了这个在 Windows 10 上使用:

CMake 3.14.5
MSVC 2019

这是 CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.9)
project (CMakeLinkTest)
add_library(myLibrary STATIC MyStar.cpp)
add_executable(CMakeLinkTest StarFactory.cpp main.cpp)
target_link_libraries(CMakeLinkTest myLibrary)

应用程序包含 main.cpp:

#include <iostream>

int main(int argc, char *argv[]){
std::cout << "Hello World!" << std::endl;
return 0;
}

和一个名为 StarFactory 的单例类。

StarFactory.h:

#include<string>

class StarFactory
{
public:

static StarFactory* instance();
~StarFactory() {};

std::string registerStarType(std::string a_type);

private:

StarFactory() {};

static StarFactory* mp_instance; // Singleton instance
};

StarFactory.cpp:

#include <iostream>
#include "StarFactory.h"

StarFactory* StarFactory::mp_instance = 0;

StarFactory* StarFactory::instance()
{
if ( mp_instance==0 )
mp_instance = new StarFactory;

return mp_instance;
}

std::string StarFactory::registerStarType(std::string a_type)
{
std::cout << "registerStarType: " << a_type << std::endl;
return a_type;
}

最后,一个静态库包含 MyStar 类,它注册了自己全局初始化时的单例。

MyStar.cpp:

#include<string>
#include "StarFactory.h"

class MyStar
{
public:
MyStar() {
StarFactory* s = StarFactory::instance();
//s->registerStarType("MyStar");
};
};

MyStar myStar;
std::string starName = StarFactory::instance()->registerStarType("MyStar");

现在看看会发生什么。如果我将 MyStar.cpp 直接链接到应用程序中,我会看到:

>CMakeLinkTest.exe
registerStarType: MyStar
Hello World!

如果将 MyStar.cpp 链接到 MyLibrary.lib 并将其链接到我看到的应用程序:

>CMakeLinkTest.exe
Hello World!

因此,库对应用程序单例的调用(MyStar.cpp 的最后一行)不起作用。

有人能解释一下吗?

最佳答案

如 engf-010 所述,如果未使用静态库中定义的符号,链接器将不会将其放入最终二进制文件中。

使用 CMake 解决问题的一种方法是使用 OBJECT 库而不是 STATIC 库。

关于c++ - Windows C++ 静态库在初始化期间无法访问外部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58765494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com