0

Hello,
I'm wanting to have multiple .cpp files in one project. I have three files:
"Main.cpp"
"Secondary.cpp"
"Main.h"
This is the content of Main.cpp:

#include "Main.h"
#include <iostream>
void Engine();

int main()
{
    b = 10;
    a = 5;
    std::cout << a << b;
    Engine();
}

This is the content of Secondary.cpp:

#include "Main.h"
#include <iostream>

void Engine()
{
    std::cout << std::endl << a;
}

This is the content of Main.h:

int a;
int b;

When I attempt to compile the project, it opens another file, called "locale_facets.tcc". It gives an error on line 2497: "multiple definition of `a'" as well as "multiple definition of `b'".

What did I do wrong?

3
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by Chuckleluck
0

I would think that "locale_facets.tcc" also uses two variables called a and b. Try changing a and b in Main.h to something else and see if that corrects the problem.

0

Nope. I changed the names to "George" and "Washington" and I get the same error.

EDIT: If it helps, I'm using Windows 7 on an HP Laptop, and I'm using Code::Blocks to compile this.

Edited by Chuckleluck: forgot my system stuff

0

If you mean that you get the same error for a and b, then it has nothing to do with YOUR a and b. There must be an a and b in iostream, since you include that twice. Try knocking out one of the iostream includes.

0

What is happening is that, because the header file is being included in both of the compiled files, the two globals are indeed being re-declared, once in each file. You need to change the header so that both are declared as extern :

#ifndef MAIN_H
#define MAIN_H 1

extern int a;
extern int b;

#endif

Then you need to actually declare the variables in either main.cpp or secondary.cpp (but not both):

#include "Main.h"
#include <iostream>
void Engine();

int a;
int b;

int main()
{
    b = 10;
    a = 5;
    std::cout << a << b;
    Engine();
}

The declaration in main.cpp is the actual declaration; the one in the header is just to allow other files to know that they exist.

Note also the use of include guards, which are to prevent a different sort of redefinition issue.

0

Ah, I see. Thank you.
Would the extern work for other data types, classes, functions, etc.?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.