I have a problem with GCC. It's unable to find my global variable. I created a sample C++ project to isolate the problem:
a.cpp:
#include "b.h"
const char * const g_test = "blah blah";
int main(){
test();
return 0;
}
b.cpp:
#include <iostream>
#include "a.h"
using namespace std;
void test(){
cout << g_test;
}
a.h:
extern const char * const g_test;
b.h:
void test();
I compile it like this:
$ g++ -o a.o -c a.cpp
$ g++ -o b.o -c b.cpp
$ g++ -o test a.o b.o
b.o: In function `test()':
b.cpp:(.text+0x7): undefined reference to `g_test'
collect2: error: ld returned 1 exit status
Changing the order of object files in last command doesn't change anything.
Why does linker throw an error? I was expecting to just create an executable printing "blah blah", but somehow the error appears. I don't see any reason it should fail.
So when we try to assign it a value in the main function, the linker doesn't find the symbol and may result in an “unresolved external symbol” or “undefined reference”. The way to fix this error is to explicitly scope the variable using '::' outside the main before using it.
You can fix the errors by including the source code file that contains the definitions as part of the compilation. Alternatively, you can pass . obj files or . lib files that contain the definitions to the linker.
c file. The error: undefined reference to function show() has appeared on the terminal shell as predicted. To solve this error, simply open the file and make the name of a function the same in its function definition and function call. So, we used to show(), i.e., small case names to go further.
You can fix undefined reference in C++ by investigating the linker error messages and then providing the missing definition for the given symbols. Note that not all linker errors are undefined references, and the same programmer error does not cause all undefined reference errors.
As a const variable g_test
has only internal linkage, i.e. can only be used in the .cpp file it is defined. In order to give a const variable global linkage (i.e. make it usable from other source files) you have to add the extern
keyword, i.e.:
#include "b.h"
extern const char * const g_test = "blah blah";
int main(){
test();
return 0;
}
Alternatively you can include a.h
at the beginning. In that case the extern
forward declaration is known to the compiler when translating a.cpp
.
The best solution however is to move the definition of g_test
(without extern
keyword ) into the header file. The reason being that in this way the compiler knows the definition of g_test
in every compilation unit and is for example able to evaluate const expressions using it at compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With