c:了解变量的意外行为

c: understanding unexpected beahvior of variables

我有以下一组文件:

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);
}

当我编译上面的解决方案时,我得到

LNK2005 error `char *path` already defined

但是,如果我在 file1.h 中将 char* path 更改为 extern char* path;

extern char* path;

并在 file2.c 中这样定义它:

char *path = "C:\test"

然后一切正常。但我无法理解行为上的差异。有人可以解释一下吗?

如果您手动将 fileh.h 的内容包含到 file2.c 和 file3.c 中,它们将是:

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);
}

当编译和链接这两个文件时,链接器会看到两个名为path 的全局变量。这就是链接器错误的原因。

当你使用

extern char* path;

在file1.h中,它只是提供了一个声明。可以根据需要在尽可能多的编译单元中声明一个变量。它只能被定义一次。因此,更改 file1.h 以便仅声明 path 并在 file2.c 中定义它可以解决问题。