-1

So I'm using visual studio and I have 3 files: my.h

#pragma once
extern int foo;
void print_foo();
void print(int);

my.cpp

#include<iostream>
#include "my.h"

void print_foo()
{
    std::cout << foo;
}

void print(int i)
{
    std::cout << i;
}

and use.cpp

#include "my.h"




int main()
{
    foo = 7;
    
    print_foo();
    print(99);


}

When I try to debug it gives me 3 linking errors: 1 unresolved externals unresolved external symbol "int foo" unresolved external symbol "int foo" Does anyone know what the problem is? Also can anyone like kinda explain what linking does specifically? Like say I have 2 object files does linking just combine them and technically just copy the code from one file into one combined file? I get that's not what really happens but can I think of it like that?

1 Answers1

3

With extern int foo you are declaring that somewhere else there is foo defined, but you do not actually define it anywhere. You can, for example, modify use.cpp adding before main():

int foo;
francesco
  • 7,189
  • 7
  • 22
  • 49