1
votes

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.

1
The variables you declare, do you define them anywhere? In which source file? Do you build with that source file?Some programmer dude
@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)Prakhar Verma
a variable declaration that uses extern and has no initializer is not a definition. this line solved everything.Prakhar Verma

1 Answers

4
votes

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.