lekroif
lekroif

Reputation: 992

C++: Linking files with GCC compiler

I have three files : myh.h; my.cpp; use.cpp. Here are the contents of the files:

myh.h

extern int foo;
void print_foo();
void print(int);

my.cpp

#include "myh.h"
#include <iostream>
void print_foo()
{
    std::cout<<foo<<std::endl;
}
void print(int i)
{
    std::cout<<i<<std::endl;
}

use.cpp

#include "myh.h"
int main()
{
    foo=7;
    print_foo();
    print(99);
    return 0;
}

GCC spews out the following error:

my.o:my.cpp:(.text+0x7): undefined reference to `foo'
use.o:use.cpp:(.text+0x10): undefined reference to `foo'
collect2: ld returned 1 exit status

I compile the files using the -c command and it doesn't give errors. I link using the following command:

g++ -o final my.o use.o

What is the problem here, I read other topics with similar problems, and the case here is just strange .....

For the curious this is an exercise drill from Stroustrup's book Programming principles of using C++

Edit: I did as dasblinkenlight said, and in use.cpp I added an int in front of foo (so now foo is defined), but I still get this error:

my.o:my.cpp:(.text+0x7): undefined reference to `foo'
collect2: ld returned 1 exit status

Which tells me that it is not defined in my.cpp also? If I have to define it everywhere what is the point of including it in the header file, or how should this be approached more appropriately?

Upvotes: 2

Views: 467

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

The problem is that foo is declared but not defined. You need to define foo in exactly one of the translation units, e.g.:

int foo = 0;

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You get a linker error because you declared foo, but you never defined it.

extern int foo is only a declaration; it does not cause allocation of memory for the foo variable, only promises that you will do it at some other place. To fix it, you need to add this line to one of the cpp files, like this:

#include "myh.h"
int foo;
int main()
{
    foo=7;
    print_foo();
    print(99);
    return 0;
}

Upvotes: 8

Related Questions