I'm a newcomer to C++. I'm having trouble building a simple multi-file project with g++
. Here are my files:
something.h
class Something
{
public:
void do_something() const;
} thing;
something.cpp
#include <iostream>
#include "something.h"
void Something::do_something() const
{
std::cout << "Hello!" << std::endl;
}
main.cpp
#include "something.h"
int main()
{
thing.do_something();
}
Here is what I tried:
g++ main.cpp
gives an error thatdo_something
is an undefined reference, which makes sense because the compiler has no ideasomething.cpp
has anything to do withsomething.h
.g++ main.cpp something.cpp
: there are 'multiple definitions' ofthing
, even though I clearly defined it only once.g++ -c main.cpp something.cpp
: no errors! However, when I try runningg++ *.o
it gives me the same error as above, so I'm thinking this is a linker error.
Can anyone explain how to compile a multi-file project, and why my approach isn't working? I'm pretty confused right now because above is what most of the C++ examples on Stack Overflow look like.
Sidenotes:
I did try the suggestions here, but they didn't address linking issues with headers specifically.
I'm not trying to redefine
thing
inmain
; if I wanted to do that, I would have typed upSomething thing
.