3

Making some development, I came to very strange problem. I need to declare pointer in header file and I would like to assign it in cpp file. Please see this snippet:

ptr.h

#ifndef PTR_H
#define PTR_H

int* ptr;

#endif // PTR_H

ptr.cpp

#include "ptr.h"

void init() {
    ptr = new int;
}

void destroy() {
    delete ptr;
}

main.cpp

#include "ptr.h"

int main() {
}

(Yes, I know, that the code is very poor in terms of memory security, but that's not the point here)

The compilation using command:

g++ ptr.cpp main.cpp

brings me the following error:

/tmp/ccBvaGqX.o:(.bss+0x0): multiple definition of `ptr'
/tmp/ccmJWQcS.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

Do you happen to know, why is that so? I mean, even though I have proper include guards, it turns out that the compiler sees multiple definition of int *p.

I should also point out, that in my actual code, this pointer is not raw pointer and I'm using namespace there. But it doesn't change anything in terms of compilation error.

EDIT: Please, keep in mind my question. I know, that declaring extern int* ptr would solve the issue, but my question is different. Why, since I have proper include guards, compiler sees multiple definition of ptr?

Szał Pał
  • 31
  • 4
  • 1
    Ehh, I see StackOverflow community has fallen... I know, that I can declare it `extern`, but that's not the question. I'm asking, why there's multiple definition, not how to solve this issue – Szał Pał Jun 04 '17 at 14:10
  • 1
    There's multiple definition because it's declared in a header file, and that header file is included in multiple code files. That much should be obvious if you understand what `#include` does. – Cody Gray - on strike Jun 04 '17 at 14:37

0 Answers0