• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to properly include classes?

 
Lazaro Caruso
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
it's a very basic problem. I've got those files:

MyClass.h

MyClass.cpp

main.cpp


And as you can see, I get error about undefined reference. Ok I know that in main.cpp I can include MyClass.cpp instead of MyClass.h and it will work, but I am pretty shure that it is not proper :/ I would like it to work exactly as string class. So after including iostream, we can use std::string without any errors regarding undefined reference. We also don't need to write: class string; before main().
So could you tell me how do you do it?
 
Rob Spoor
Sheriff
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How are you compiling that? I've copied your classes and ran g++ MyClass.cpp main.cpp and it compiled just fine.
 
Lazaro Caruso
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I compiled:
g++ main.cpp -o main

Your soulution works, so thank you But why we don't have to compile in that way, when dealing with iostream and std::string?
 
Rob Spoor
Sheriff
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Those are on the default library path and are linked automatically.

For your information, you can compile each source file separately. You'll need to use the -c flag for that, and the extension is usually .o. For instance:
g++ -c MyClass.cpp -o MyClass.o
g++ -c main.cpp -o main.o
g++ MyClass.o main.o -o main

The first two lines compile the source files into object files. The third line then links these two object files (and any libraries on the library path) into the executable.
 
Lazaro Caruso
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks again for your explanation! That really helped
 
Rob Spoor
Sheriff
Pie
Posts: 20514
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic