0

With the following files, I get the error multiple definition of 'a' even though I only defined it once?

header.cpp

add (int x, int y) {
    return x+y;
}

header.h

#if !defined(header)
#define header

int add (int x, int y);

int a;

#endif

main.cpp

#include <iostream>
#include "header.h"
#pragma once

using std::cout;
using std::endl;


int main() {
    cout << "hi" << endl;
    cout << a << endl;
}

The code is copied exactly

Julian Goddard
  • 431
  • 1
  • 4
  • 10
  • [Declaring variables in header files C++](http://stackoverflow.com/questions/38942013/declaring-variables-in-header-files-c) – Arash Mar 31 '17 at 21:57
  • It does help if you provide actual code. As provided, your code will not result in multiple definitions (and will not compile either). – Peter Mar 31 '17 at 22:00
  • 2
    Are you absolutely sure that you didn't include header.h in header.cpp? I suspect that you did. – eerorika Mar 31 '17 at 22:02
  • *I get the error* -- Is this a compiler error, or linker error? If you included `header.h` in both `header.cpp` and `main.cpp`, then that is a linker error, not a compiler error. So did you post the entire `header.cpp` file? – PaulMcKenzie Mar 31 '17 at 22:03
  • And, BTW, `#pragma once` is unnecessary with an include guard. But, if you do use it, use it in header files, not source files. – Peter Mar 31 '17 at 22:05
  • @PaulMcKenzie I get the error when compiling – Julian Goddard Mar 31 '17 at 23:07

0 Answers0