Search code examples
c++structlinkerheader-filesobject-files

C++ Multiple Definition of Struct


I have header util.hpp containing a simple struct:

// util.hpp

struct Point {
  float x;
  float y;
};

Two cpp files, let's call them a.cpp and b.cpp, both include util.hpp:

// a.cpp

#include "util.hpp"

void funcA(float _x, float _y) {
  Point p;
  p.x = _x;
  p.y = _y;
  // ...
}
// b.cpp

#include "util.hpp"

void funcB(float _x, float _y) {
  Point p;
  p.x = _x;
  p.y = _y;
  // ...
}

int main() {
  // ...
}

When I compile a.cpp and b.cpp individually and then link them together I get no errors.

Why is that? Since I include util.hpp in both files, wouldn't we have a double definition of struct Point? When I for example add a variable definition to util.hpp like this:

// util.hpp

struct Point {
  float x;
  float y;
};

// New variable
int foo;

I get the following error when linking:

g++ a.o b.o -o test -O0
b.o:(.bss+0x0): multiple definition of `foo'
a.o:(.bss+0x0): first defined here

which makes sense to me, but why doesn't the same error occur for the struct?


Solution

  • b.o:(.bss+0x0): multiple definition of `foo'

    having

    // util.hpp
    ...
    // New variable
    int foo;
    

    each time you include util.hpp you define again the global variable foo, producing your error

    in the header file just declare it (extern int foo;) and define it on one source file

    There is not the same problem for the struct Point because this is a type definition, not a global variable definition