Eclipse/GCC:对Extern变量的未定义引用

时间:2022-11-23 20:40:55

sorry if this is a repeated question, but I've been searching around for a couple of hours, and I'm getting conflicting answers... and what's worse, none of them are working.

如果这是一个重复的问题,我很抱歉,但是我已经找了几个小时了,我得到的答案是相互矛盾的……更糟糕的是,他们都没有工作。

It's a simple matter. I have many source files, and I have some common parameters that I want to be in a single file, say "Parameters.h". I want to set these parameters (once) at runtime, by passing them as arguments to the program.

这是一个简单的问题。我有很多源文件,我有一些常用的参数我想放在一个文件中,比如" parameters .h"我想在运行时设置这些参数(一次),将它们作为参数传递给程序。

PS: I know that a better way of doing it is to pass everything as arguments to functions, but it's a chunky piece of code and I need to get a result soon without making too many changes.

PS:我知道更好的方法是将所有参数传递给函数,但是这是一段很粗的代码,我需要在不做太多修改的情况下尽快得到结果。

Here is a minimal working example:

这里有一个最小的工作例子:

Parameters.h

Parameters.h

#ifndef PARAMETERS_H_
#define PARAMETERS_H_

extern int Alpha;

#endif

main.cpp

main.cpp

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

int main(int argc, char * argv[])
{
    const int Alpha = 12.0;
}

Functions.cpp

Functions.cpp

#include "Parameters.h"

double Foo(const double& x)
{
    return Alpha*x;
}

When I compile with

当我编译的

gcc main.cpp Functions.cpp

I get the error "Functions.cpp:(.text+0xa): undefined reference to `Alpha'".

我得到了错误的“Functions.cpp:(.text+0xa):未定义的‘Alpha’”。

1 个解决方案

#1


17  

You have declared a global variable named Alpha, but you haven't defined it. In exactly one source file, write at file scope:

您已经声明了一个名为Alpha的全局变量,但是还没有定义它。在一个源文件中,在文件范围内写:

int Alpha;

or with an initializer:

或一个初始化程序:

int Alpha = 42;

Note that the local variable named Alpha you have defined within main is distinct from and completely unrelated to this global variable.

注意,在main中定义的局部变量Alpha与这个全局变量完全不相关。

#1


17  

You have declared a global variable named Alpha, but you haven't defined it. In exactly one source file, write at file scope:

您已经声明了一个名为Alpha的全局变量,但是还没有定义它。在一个源文件中,在文件范围内写:

int Alpha;

or with an initializer:

或一个初始化程序:

int Alpha = 42;

Note that the local variable named Alpha you have defined within main is distinct from and completely unrelated to this global variable.

注意,在main中定义的局部变量Alpha与这个全局变量完全不相关。