Reputation: 331
I have a header file : headerFiles.h containing following extern variable :
extern char *err_msg;
extern char recvbuf[DEFAULT_BUFLEN];
extern char sendbuf[DEFAULT_BUFLEN];
this header file is included into : Helper.h and Helper.h is included into Helper.cpp, So,
headerFiles.h --> included in --> Helper.h --> included in --> Helper.cpp
but when I am referencing the extern variables in my Helper.cpp file the compiler is giving following linking error :
Error LNK2001 unresolved external symbol "char * err_msg" (?err_msg@@3PADA)
I think it can be compiled via command line, but I want to know how to compile it using Visual C++. I have VC++ 2017 Community edition. Please help.
Upvotes: 2
Views: 829
Reputation: 522
From here:
The extern specifier is only allowed in the declarations of variables and functions (except class members or function parameters). It specifies external linkage, and does not technically affect storage duration, but it cannot be used in a definition of an automatic storage duration object, so all extern objects have static or thread durations. In addition, a variable declaration that uses extern and has no initializer is not a definition.
In other words, your code just declares that there is err_msg
(and others) variable defined(!) somewhere, relying on a linker to know where it is.
That's why you get a linker error when it's unable to locate requested name.
One possible solution is to define:
char *err_msg;
char recvbuf[DEFAULT_BUFLEN];
char sendbuf[DEFAULT_BUFLEN];
in one (and only one) of *.cpp files in your project.
Upvotes: 4