例子:
stdafx.h:
#pragma once
typedef void (__stdcall*FuncType)(int,int);
extern FuncType Func1 = NULL;
foo.cpp:
int main()
{
printf("%x\n",&Func1);
return 0;
}
foo2.cpp:
void call()
{
printf("%x\n",&Func1);
}
假设 foo.cpp,foo2.cpp 都包含 stdafx.h
链接器错误:
1>fooTest.obj : error LNK2005: "void (__stdcall* Func1)(int,int)" (? Func1@@3P6GXHH@ZA) already defined in stdafx.obj
1>foo2.obj : error LNK2005: "void (__stdcall* Func1)(int,int)" (?Func1@@3P6GXHH@ZA) already defined in stdafx.obj
1>C:\Users\****\Documents\Visual Studio 2005\Projects\fooTest\Debug\fooTest.exe : fatal error LNK1169: one or more multiply defined symbols found
使用 static 而不是 extern 可以很好地编译,但是源文件使用它们自己的 Func1 版本,这是 Not Acceptable ,因为我需要它们共享同一个变量。
请告诉我哪里做错了!
最佳答案
我想您必须定义变量Func1
,它只是在头文件中声明,仅在您的一个源文件中,而不是成两半;并且您不能在那里将其声明为静态的,因为其他翻译单元将看不到它。我不会在头文件中将其设置为 NULL
,而是在您实际定义变量的(一个)源文件中。
关于c++ - 在 Visual Studio 中访问来自多个源文件的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42214155/