简体   繁体   English

使用extern时未定义的引用

[英]undefined reference when using extern

I have the following setup (hopefully this is not too bare an example): 我有以下设置(希望这不是一个例子):

Ah

typedef std::map<unsigned int, float> MyClass;
extern MyClass inst;

A.cpp A.cpp

MyClass inst;

Bh BH

#include <A.h>
void foo();

B.cpp B.cpp

#include <B.h>
void foo {
    inst.myClassFunc();
}

Now, when I use inst in B.cpp I get undefined reference to inst . 现在,当我在B.cpp使用inst时,我得到undefined reference to inst

Any idea on how to fix this? 有关如何解决此问题的任何想法?

I know this question is old, but it still might be helpful for someone. 我知道这个问题很老,但它对某些人来说仍然有用。

The global variable (here: MyClass inst ) should not be extern for the compilation unit which define it (here: A.cpp ) 全局变量(这里: MyClass inst不应该是 定义的编译单元的 extern (这里: A.cpp

One way to achieve this: 实现这一目标的一种方法:

  • declare your global variable in a separate header (let's say global.h ) and include this header in the *cpp using these. 在一个单独的头文件中 声明你的全局变量(比如说global.h ),并使用这些在* cpp中包含这个头文件。
  • remove the extern keyword for the compilation unit which define them (eg with #ifdef ) : 删除定义它们的编译单元的extern关键字(例如#ifdef ):

global.h looks like: global.h看起来像:

#ifdef A_H_
  #define EXTERN
#else
  #define EXTERN extern
#endif

EXTERN MyClass inst;

while Ah looks like: 而阿看起来像:

#ifndef A_H_
#define A_H_

// your header content (without globals)

#endif /* A_H_ */

and A.cpp: 和A.cpp:

#include "A.h"
#include "global.h" // after A.h inclusion, we need A_H_ definition

Hope it helps! 希望能帮助到你!

This is too bare an example to work out what's going on. 这只是一个例子,可以解决正在发生的事情。 However, based on the above it's entirely possible that when it hits the failing line the compiler has no knowledge of what's actually in MyClass and therefore cannot resolve MyClassFunc . 但是,基于上述情况,完全有可能当它遇到失败的行时,编译器不知道MyClass实际存在什么,因此无法解析MyClassFunc

We would need to see the definition of MyClass and know where it is to answer for sure. 我们需要看看MyClass的定义并知道它的确切位置。

You have to compile the above mentioned file A.cpp as 你必须编译上面提到的文件A.cpp as

g++ -c A.cpp
g++ -c B.cpp

and then while creating the executable you should write the command as follows: 然后在创建可执行文件时,您应该按如下方式编写命令:

g++ A.o B.o

从您发布的基本示例代码中我会说您忘记了在B.cpp文件中#include <Bh>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM