Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 466
MGA Avatar asked Oct 10 '13 00:10

MGA


1 Answers

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.

like image 113
Igor Tandetnik Avatar answered Sep 22 '22 01:09

Igor Tandetnik