Eclipse / GCC: Undefined External variable reference

Sorry if this is a recurring question, but I searched for a couple of hours and I get conflicting answers ... and even worse, none of them work.

This is a simple question. I have many source files, and I have some common parameters that I want to be in a single file, for example, "Parameters.h". I want to set these parameters (once) at run time, passing them as arguments to the program.

PS: I know that the best way to do this is to pass everything as arguments to a function, but this is a short part of the code, and I need to quickly get the result 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

 gcc main.cpp Functions.cpp 

I get the error message "Functions.cpp :(. Text + 0xa): undefined link to` Alpha '".

+7
c ++ gcc eclipse global-variables linker
source share
1 answer

You declared a global variable named Alpha , but you did not define it. In exactly one source file, write in the file area:

 int Alpha; 

or with an initializer:

 int Alpha = 42; 

Note that the local variable named Alpha , which you defined in main , is different from this global variable and is not completely associated with it.

+17
source share

All Articles