0

im searching the internet for about half an hour because of a (actually basic and simple) problem in C++. Maybe im missing something, but I don't know what. Lets say, i have 3 files: "main.cpp", "dosomething.cpp" and "Header.h".

"Header.h":

#pragma once
#ifndef HEADER_H
#define HEADER_H
char text[] = "This is a text";
#endif // !HEADER_H

"main.cpp"

#include <stdio.h>
#include <iostream>
#include "Header.h"

using namespace std;

void main() {
    cout << text << endl;       
}

and "dosomething.cpp"

#include "Header.h"
void dosth() {  

}

Now the compiler/linker tells me that "text" is already defined in another file. Why? I know how guard idioms such as #pragma once and #ifndef etc. work - atleast I think so. I have no idea whats wrong here. The code itself works (when not including the header in "dosomething.cpp").

Any idea?

Edit: Im using Visual Studio 2015

Florian
  • 36
  • 3
  • 1
    make `text` `const`, you're breaking the one definition rule – David Mar 28 '16 at 16:38
  • 5
    http://stackoverflow.com/questions/7926224/header-include-guards-dont-work – Unimportant Mar 28 '16 at 16:40
  • 2
    Just to expand on user1320881's comment: What's happening here is this: When you compile main.cpp, Header.h gets included exactly once; when you compile dosomething.cpp, Header.h gets included exactly once; and now both of them have definitions of `text` in, and the linker complains. Your header guards are doing their job, but preventing this problem is not their job. – Gareth McCaughan Mar 28 '16 at 16:52
  • find . -name '*.h' -o -name '*.hpp' | xargs -n1 -d '\n' grep "#define HEADER_H" | sort | uniq -cd – fiorentinoing Aug 03 '18 at 08:52

1 Answers1

0

You need to put extern keyword. C/C++ does for every .c/.cpp file will combine the text of files and all definitions will be merged in the linking step. If you write 'extern' before the header variable, you can define it in just one C++ file, and all other files will reuse it. The linker will use just one instance of the variable you externed it to.

So in header.h

#pragma once
extern char text[];

main.cpp remains the same, but"dosomething.cpp" changes slightly

#include "Header.h"

(...)
char text[] = "...";

(...)

https://en.wikipedia.org/wiki/External_variable

Ciprian Khlud
  • 434
  • 3
  • 6