C++ 静态类成员未在 * 静态库中初始化 * [英] C++ static class member not initialized in a * static library *

查看:41
本文介绍了C++ 静态类成员未在 * 静态库中初始化 *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在使用 C++ 时遇到了一个烦人的问题.

I'm currently facing an annoying issue with C++.

其实,我什至不明白为什么过去20年我没有面对它:(

Actually, I don't even understand why I didn't face it for the past 20 years :(

在我目前的情况下,我们大量使用 C++ 可执行文件(主要在 Linux 嵌入式系统中)静态与我们的专有静态库链接.出于技术和优化原因,我们确实使用了静态库.

In my current context, we heavily use c++ executables (mostly in Linux embedded systems) statically linked with our proprietary static libs. And we do use static libs for technical and optimization reasons.

在过去的几年里,确实,我曾经创建共享库...

Over the past years, indeed, I used to create shared libs though...

于是我开始写一些带有静态类成员的类.例如如下:

So I began to write some classes with static class members. Such as follow:

class Inner
{
public:
   Inner()
   {
     std::cout << "CTOR Inner" << std::endl;
   }
};

class A
{
static Inner _inner;

...
};

// in the .cpp

Inner A::_inner;

///////////////////////

非常基本的用例,不是吗?

Very basic use-case, isn't it ?

但是在与 lib 链接的单元测试中,我在控制台中看不到 std::cout 语句.然而,如果我将我的类 Inner 和 A 移动到可执行的源代码中......它工作正常.

But in my unit-tests, linked with the lib, I can't see the std::cout statement in the console. Whereas, if I move my class Inner and A into the executable source-code...it works fine.

我确定这是一个非常基本的问题,而且我意识到过去几年我从未遇到过.这是与编译器有关的问题吗?请注意,我在 Windows 和 Linux(Debian、Gcc 4.9)上测试了这两种情况.

I'm sure it's a very basic issue and I realize I've never faced over the past years. Is it an issue related to the compilers ? Please note that I tested both cases on Windows and Linux (Debian, Gcc 4.9).

欢迎提出任何想法.

Z.

推荐答案

您必须以某种方式实际使用 A::_inner 否则将不会包含该部分代码.要么使用该文件中的其他内容,要么使用该文件中的其他内容.链接器不必在从未使用过的翻译单元中进行链接,即使它们会产生可观察到的副作用.

You have to actually use A::_inner somehow or that part of code won't be included. Either that or use something else in that file. Linkers don't have to link in translation units that are never used, even if they'd have observable side effects.

如何强制包含;未使用"库中的对象定义

这篇关于C++ 静态类成员未在 * 静态库中初始化 *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆