简体   繁体   中英

Eclipse/GCC: Undefined Reference to Extern Variable

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.

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.

Here is a minimal working example:

Parameters.h

#ifndef PARAMETERS_H_
#define PARAMETERS_H_

extern int Alpha;

#endif

main.cpp

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

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

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'".

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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