1

I'm compiling 2 C++ files together. 4 if you include the header files. The problem is, I keep getting "Duplicate Symbol" errors when the linker tries to link the files together.

Here are my files.


main.h

int test2();

main.cc

#include "main.h"
#include "test.h"

int test2(int test) {
    return 0;
}

int main() {

    test2(test());
    return 0;
}

test.h

int hello = 10;
int test();

test.cc

#include <iostream>
#include "test.h"
using namespace std;

int test() {
  cout << hello << endl;
  return 0;
}

I think I'm doing something simple wrong. Can someone please point out what I'm doing wrong. Here's how I'm compiling the files.

c++ main.cc test.cc -o main

Here's the error I get:

duplicate symbol _hello in:
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/main-3becdd.o
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/test-e84473.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
user3842667
  • 13
  • 1
  • 3

2 Answers2

13

In header file, declare the variable:

extern int hello;

In exactly one source file, define the variable:

int hello = 10;

Do not define variables in headers - that's equivalent to defining them in every source file that includes the header, and that's what's causing your linker error.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
0

You can simply define hello as a "static" (global) variable

static int hello = 10;

More information is mentioned in a similar question:

Duplicate symbols while linking

ayehia
  • 85
  • 12