Reputation: 21
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
Reputation: 36423
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
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
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