C ++链接器奇怪的行为:静态成员变量 [英] C++ linker strange behavior: static member variable

查看:86
本文介绍了C ++链接器奇怪的行为:静态成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我陷入了链接器错误,需要一些帮助.我正在使用MSVC.

I'm stuck in a linker error and need some help. I'm using MSVC.

一开始,我是这样做的:

At the beginning, I made this:

/* graphics_app.h */
#ifndef DK_GRAPHICS_APP_H
#define DK_GRAPHICS_APP_H
...
class GraphicsApp {
private:
    static GraphicsApp* self;
...
};

GraphicsApp* GraphicsApp::self = nullptr;
#endif /* DK_GRAPHICS_APP_H */

该标头曾经可以工作...并且我做了一些改进,但是该静态成员没有任何变化.

This header used to work... and I made some improvements, but nothing about that static member changed.

但出乎意料的是,我收到此链接器错误消息:

but unexpectedly I got this linker error message:

LNK2005 "private: static class GraphicsApp * GraphicsApp::self" (?self@GraphicsApp@@0PEAV1@EA) already defined in main.obj.
LNK1169 one or more multiply defined symbols found.

因此,我将此标头分为.h和.cpp:

So, I separated this header into .h and .cpp:

/* graphics_app.cpp */
#include "graphics_app.h" 
...
GraphicsApp* GraphicsApp::self = nullptr;

但是我又遇到了一个错误:

but I got another error:

LNK2001 "private: static class GraphicsApp * GraphicsApp::self" (?self@GraphicsApp@@0PEAV1@EA) unresolved external symbol.
LNK1120 1 unresolved externals.

为什么发生这些怪异的行为?我该如何解决?

Why these weird behavior happens & how can I fix?

我制作了测试版本以简化问题. 当我使用自定义的include目录时,就会发生此事. 例如

I made test version to make problem simper. This thing happens when I use my custom include directory... such as

#include <dk/graphics_app.h>

代替

#include "graphics_app.h"

所以..一个新问题是,如何在使用自定义include目录时解决此问题?

So.. a new problem is, how can I fix this whilst using my custom include directory?

使事情变得简单得多.

To make Thing much simpler..

推荐答案

此标头曾经可以工作...并且我做了一些改进,但该静态成员没有任何变化.

This header used to work... and I made some improvements, but nothing about that static member changed.

您的标头写得不正确:您不应将具有外部链接的实体的定义放入标头文件中.只要您将头文件包含在一个并且只有一个翻译单元中,它就可以工作".但是,一旦将其包含在两个或多个不同的翻译单元中,就会出现多个定义"错误.正是您的情况.

Your header is written incorrectly: you are not supposed to put definitions of entities with external linkage into header files. It could "work" as long as you included your header file into one and only one translation unit. But once you include it into two or more different translation units, you get the "multiple definition" error. Which is exactly what happened in your case.

因此,我将此标头分为.h和.cpp

So, I separated this header into .h and .cpp

这是正确的做法.现在,您必须确保将graphics_app.cpp作为程序的一部分进行编译(并链接).这是您忘记做的事.编译器/链接器/构建系统无法以某种方式神奇"地意识到,刚创建的graphics_app.cpp应该是项目的一部分.

This is the right thing to do. Now you have to make sure your graphics_app.cpp is compiled (and linked) as part of your program. This is something you forgot to do. The compiler/linker/build system cannot somehow "magically" realize by itself that your freshly created graphics_app.cpp is supposed to be part of your project.

这篇关于C ++链接器奇怪的行为:静态成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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