I have a simple project broken up into the following source files:
my.h:
#ifndef MY_H
#define MY_H
extern int val;
void print_val();
#endif
my.cpp:
#include "my.h"
#include <iostream>
void print_val()
{
std::cout << val;
}
main.cpp:
#include "my.h"
int main()
{
val = 4;
print_val();
return 0;
}
When I compile I receive the following errors:
1>main.obj : error LNK2001: unresolved external symbol "int val" (?val@@3HA)
1>my.obj : error LNK2001: unresolved external symbol "int val" (?val@@3HA)
1>c:\...\test.exe : fatal error LNK1120: 1 unresolved externals
Why is this so? I simply want to declare a variable and function in a header and define the function in a separate source file. I use Visual C++ 2010 Express, and the project is a Win32 Console app.
In your
my.cppyou probably wanted to define that extern variable of yours, like this:This will make sure the compiler actually allocates an object for this variable that can be later linked into your executable.
On a related note – make sure there’s only one definition of such
externvariable in all of your source files otherwise you’ll have duplicate symbols and linker won’t be happy with that