File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes C / C++ and the fly likes How to properly include classes? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » C / C++
Bookmark "How to properly include classes?" Watch "How to properly include classes?" New topic
Author

How to properly include classes?

Lazaro Caruso
Greenhorn

Joined: Jan 03, 2011
Posts: 12
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

Joined: Oct 27, 2005
Posts: 19692
    
  20

How are you compiling that? I've copied your classes and ran g++ MyClass.cpp main.cpp and it compiled just fine.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Lazaro Caruso
Greenhorn

Joined: Jan 03, 2011
Posts: 12
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

Joined: Oct 27, 2005
Posts: 19692
    
  20

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

Joined: Jan 03, 2011
Posts: 12
Thanks again for your explanation! That really helped
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19692
    
  20

You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to properly include classes?