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
?