0

I have following set of files:

file1.h:

char* path = "C:\\temp"

file2.c

#include "file1.h"
char* getFilePath(){
  return path;
}

file3.c:

#include "file1.h"
int main(){
  printf(" File path: %s",getFilePath);
}

When I compile the above solution, I get

LNK2005 error `char *path` already defined

However, if I change char* path to extern char* path; in file1.h:

extern char* path;

and also define it in file2.c like this:

char *path = "C:\\test"

then everything works fine. But I am not able to comprehend difference in behavior. Can somebody please explain this?

jotik
  • 17,044
  • 13
  • 58
  • 123
tryingToLearn
  • 10,691
  • 12
  • 80
  • 114
  • 2
    This is C, not C++. Don't put both tags – asimes Jun 07 '16 at 05:15
  • In file3.c I suppose you mean `printf(" File path: %s",path);`, correct? – Matteo Italia Jun 07 '16 at 05:17
  • What was your expectation? – babon Jun 07 '16 at 05:19
  • 1
    Leave aside the header file for now. What do you understand will happen if you just type in `char* path = "C:\\temp"` in every single C source file? Well, it means you have declared multiple variables with the same variable name. That is not allowed because in C each variable name must be unique within the same scope. Now back to the header file, including that into multiple source files will have the exact effect of declaring multiple variables with the same name (since the header file has no include guard). – kaylum Jun 07 '16 at 05:19
  • See this for more details: [How do I use extern to share variables between source files in C?](https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files-in-c?) – kaylum Jun 07 '16 at 05:21
  • @kaylum different source files are different scopes. It's legal to have multiple variables of the same name in some cases (e.g. if the name has internal linkage) – M.M Jun 07 '16 at 05:41
  • @M.M Yes, I was simplifying it for the OP. – kaylum Jun 07 '16 at 05:42

1 Answers1

3

If you include the contents of fileh.h manually into file2.c and file3.c, they will be:

file2.c:

// This is the definition of a global variable.

char* path = "C:\\temp"

char* getFilePath(){
  return path;
}

file3.c:

// This is the definition of a second global variable.

char* path = "C:\\temp"

int main(){
  printf(" File path: %s",getFilePath);
}

When these two files are compiled and linked, the linker sees two global variables named path. That's the reason for the linker error.

When you use

extern char* path;

in file1.h, it simply provides a declaration. A variable can be declared in as many compilation units as necessary. It can be only be defined once. Hence, changing file1.h so that path is only declared and defining it in file2.c resolves the problem.

R Sahu
  • 204,454
  • 14
  • 159
  • 270