Search code examples
cheader-filesextern

c: understanding unexpected beahvior of variables


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?


Solution

  • 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.