gpt4 book ai didi

c++ - 忽略具有单个全局变量的 cpp 文件

转载 作者:太空狗 更新时间:2023-10-29 21:00:12 28 4
gpt4 key购买 nike

我正在尝试初始化一个全局 map

std::map<long, std::string> Global_ID_Mapper;

有许多“初始化”类,例如:

struct AGlobalMapperInitializer
{
AGlobalMapperInitializer()
{
Global_ID_Mapper.insert( std::make_pair(1, "Value1") );
Global_ID_Mapper.insert( std::make_pair(2, "Value2") );
}
};

我想在应用程序启动时自动填充 map 。所以在我的一个 cpp 文件中,我只定义了那个“init”类的全局变量。

// AGlobalMapperInitializer.cpp

AGlobalMapperInitializer AGlobalMapperInitializer_Value;

Mapper 填充是 AGlobalMapperInitializer_Value 创建的副作用。

问题是,如果 cpp 除了这个全局变量之外不包含任何内容,链接器显然会忽略 cpp。当我将一些有用的其他代码放入 cpp(或在某些非空 cpp 中定义全局初始化程序)时,将调用构造函数并填充全局映射器。但是,如果 cpp 仅包含未在其他文件中引用的全局变量,则编译 cpp,obj 文件包含变量,但链接器在链接期间未提及它,并且在 exe 中丢失。

我怎么能坚持把cpp链接成exe呢?是否有一些 pragma 或虚拟代码可以放入 cpp 中以使其不被忽略?我使用 Visual Studio 2012。

最佳答案

C++ 不需要初始化全局变量 x 如果没有函数或来自同一文件(实际上是翻译单元)的变量作为 x 被引用。

参见 C++11 [basic.start.init]§4:

It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first odr-use (3.2) of any function or variable defined in the same translation unit as the variable to be initialized.

因此要强制变量初始化,您必须将其放入您实际使用的其他内容的文件中,或者直接在某处使用该变量。

关于c++ - 忽略具有单个全局变量的 cpp 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22680757/

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