asterix
asterix

Reputation: 21

g++ linker problem

I am trying to understand the keyword extern in C++ and wrote a short code to outline the meaning. Unfortunately I am doing something wrong

bla.h

int bla = 4;

test.cpp

#include <iostream>

using namespace std;

int main() {
       extern int bla;
       cout << bla << endl;
}

g++ -o test bla.h test.cpp
/tmp/ccED67jz.o: In function `main':
test.cpp:(.text+0xa): undefined reference to `bla'
collect2: ld returned 1 exit status

Upvotes: 2

Views: 391

Answers (3)

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36423

  • never define variables in headers (that is where you should use extern)
  • never declare a local extern variable, these variable are always global and declaring them locally causes confusion

What extern means is: Don't create the variable here, it already exists elsewhere. The "elsewhere" part means in a different compilation unit.

For example:

file1.c

int x;

file2.c

extern int x; /* x already exists in file1.c */

int main()
{
    x = 10;
}

Compile like this:

gcc file1.c file2.c

Upvotes: 1

orlp
orlp

Reputation: 117641

extern, the use you describe only works on globals:

bla.cpp

int bla = 4;

test.cpp

#include <iostream>

extern int bla; // use the global from bla.cpp as a global in this file

int main(int argc, char *argv[]) {
    std::cout << bla << "\n";
    return 0;
} 

Upvotes: 4

hookenz
hookenz

Reputation: 38859

Use it more like this.

test.cpp

extern int bla;

int main(int argc, char** argv)
{
    cout << bla << endl;
    return 0;
}

other.cpp

int bla;

g++ test.cpp other.cpp

Basically extern is used to make the compiler link the external variable in another object file. That could be another source file or even an external library. It also only works on globals.

Upvotes: 1

Related Questions