1

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.

KidWithAComputer
  • 311
  • 1
  • 2
  • 10
  • 3
    The variables you declare, do you *define* them anywhere? In which source file? Do you build with that source file? – Some programmer dude Oct 15 '18 at 12:00
  • 1
    Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – Peter Ruderman Oct 15 '18 at 12:01
  • @Some programmer dude , I have added the three extern variables in HeaderfFles.h, my aim is to keep all the extern variables in one place(i.e; in a seprate header file) – KidWithAComputer Oct 15 '18 at 13:10
  • `a variable declaration that uses extern and has no initializer is not a definition.` this line solved everything. – KidWithAComputer Oct 15 '18 at 13:15

1 Answers1

4

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.

John Cvelth
  • 522
  • 1
  • 6
  • 19
  • thanks @John for the explanation, --> a variable declaration that uses extern and has no initializer is not a definition. <-- so I added NULL declaration to them and the linkage issue got resolved. `extern char *err_msg=NULL; extern char recvbuf[DEFAULT_BUFLEN] = {0}; extern char sendbuf[DEFAULT_BUFLEN] = {0};` – KidWithAComputer Oct 15 '18 at 13:14