Reputation: 141
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.
Upvotes: 0
Views: 832
Reputation: 23001
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;
Upvotes: 1