0

My C++ code gets many "multiple definition" errors when compiled. A minimal example for my situation is:

//testA.h
#ifndef __FILEA_H_INCLUDED__
#define __FILEA_H_INCLUDED__

int A;
int B;

#endif

//testB.h
#ifndef __FILEB_H_INCLUDED__
#define __FILEB_H_INCLUDED__

int C;
int D;

#endif

//testA.cpp
#include "testA.h"

//testB.cpp
#include <iostream>
#include "testA.h"
#include "testB.h"

int main() {
    std::cout << C << std::endl;
}

Prepending "extern" to variable declarations solves these "multiple definition" errors but introduces "undefined reference" errors. I have tried everything I can think of to solve this - but obviously I am doing something wrong.

In case you wonder, in my real application I need the variables to be treated as global variables.

Jaeya
  • 131
  • 5

1 Answers1

1

You should declare global variables in .h file, and define them in .cpp file.

In testA.h

extern int A;

In testA.cpp

int A;

for_stack
  • 14,584
  • 2
  • 20
  • 34
  • Thanks, I didn't know a redeclaration in the .cpp was needed. – Jaeya Sep 07 '16 at 11:30
  • 1
    @Jaeya It's NOT a redeclaration, but a definition. Check [this answer](http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration) for their difference. – for_stack Sep 07 '16 at 11:36
  • Finally I get the difference :) Thanks! – Jaeya Sep 08 '16 at 08:19