Reputation: 787
So, I was going to demonstrate the problem of (non-template) implementation in C++ .h files to a college.
But right now I can't reproduce it as expected. Here's my code:
// common.h
#ifndef common_h
#define common_h
#include <iostream>
class common
{
public:
void Hello() {
// Implementation in header file
std::cout << "Hello from common" << std::endl;
}
};
#endif // common_h
// user1.h
#ifndef user1_h
#define user1_h
#include "common.h"
class user1
{
public:
user1();
private:
common g;
};
#endif // user1_h
// user1.cpp
#include "user1.h"
#include <iostream>
user1::user1()
{
std::cout << "Constructing user 1" << std::endl;
g.Hello();
}
// user2.h
// Exactly as user1.h except the class+constructor name
// user2.cpp
// Exactly as user1.cpp except the class+constructor name
// main.cpp
#include "user1.h"
#include "user2.h"
int main()
{
user1 u1;
user2 u2;
}
I'm compiling the code like this:
g++ -c -g -O0 -fno-lto -fno-inline-small-functions user1.cpp
g++ -c -g -O0 -fno-lto -fno-inline-small-functions user2.cpp
g++ -c -g -O0 -fno-lto -fno-inline-small-functions main.cpp
g++ user1.o user2.o main.o
Nothing fails and program works as expected.
Why am I not getting a "multiple declarations" error on the "Hello" function in common.h?
I looked into the object files (using objdump) and I see this tag: LINK_ONCE_DISCARD. Could this be the reason? Can anyone supply more details? I'm sure I've seen this before so something must have change (maybe from a compiler update or something).
Compiler version:
>g++ --version
g++ (Rev2, Built by MSYS2 project) 12.1.0
Copyright (C) 2022 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Upvotes: 0
Views: 65
Reputation: 787
Thanks to @BoP, here's the answer:
https://en.cppreference.com/w/cpp/language/inline
My "Hello" function is inline because it is defined inside a class declaration.
Upvotes: 0