unresolved external

Hello all!
This is my header code, my1.h:

extern int t;
void print(int);
void print_t();

And this the my2.cpp code:

#include <my1.h>
#include <iostream>

void print(int i)
{
cout << i << endl;
}

void print_t()
{
cout << t <<endl;
}

And this is my use.cpp to uses those files:

#include <my1.h>
#include <conio.h>

int main()
{
t = 12;
print(99);
print_t();
_getch();
return 0;
}

for the use.cpp file I have added the my2.cpp file to that.

When I run the use.cpp, the following errors will appear:

Error 3 error LNK1120: 1 unresolved externals C:\Users\tom\documents\visual studio 2010\Projects\use\Debug\use.exe 1

Error 1 error LNK2001: unresolved external symbol "int t" (?t@@3HA) C:\Users\tom\documents\visual studio 2010\Projects\use\use\my2.obj

Error 2 error LNK2001: unresolved external symbol "int t" (?t@@3HA) C:\Users\tom\documents\visual studio 2010\Projects\use\use\use.obj

My machine in Windows 7, and I use MS Visual studio 2010 IDE.
Is there anyone to help me solve those errors please?


Last edited on
change #include <my1.h> to #include "my1.h"
I did that but errors still exist as before!
oh, now I understand: you tell the compiler with extern int t; that in another file int t exists, but it doesn't. You should add int t; to my2.cpp or use.cpp.
Sorry I can't understand! I don't have int t in another file, and in addition if I declare an extern int with another name (say, extern int foo) the problem still exists and only the name of 't' will replace with 'foo' in error messages.

I think whatever problem there is it's about extern int t
I declared the extern int t in my1.h and defined it in my2.cpp and used in use.cpp. It should works easily but doesn't!
Sorry I can't understand! I don't have int t in another file,


What you have to understand is that you need int t; in another file, because currently you have no definition of the variable, only a declaration.

In "header.h"
1
2
3
// ...
extern int t ; // a declaration of t.
// ... 


In "header.cpp"
1
2
3
4
#include "header.h"
// ...
int t = 0 ;   // The definition of t should be at global scope.
// ... 


In "main.cpp"
1
2
3
4
5
6
7
#include <iostream>
#include "header.h"

int main()
{
    std::cout << t << '\n' ;
}


Last edited on
I think you want to pass the value of t on the print_t() function. In this case t must contained on print_t() arguments as:
1
2
3
void print_t(int t){
  cout<<t<<'\n';
}

In this case not use external for t. This is common variable passing by value.
External used for precompiled libraries to .obj. #include works like included code has writen in the include point.
Last edited on
Thank you for all you nice guys, especially cire. The problem solved. thank you again.
Topic archived. No new replies allowed.