C++ classes and headers

Started by
2 comments, last by Zahlman 16 years, 9 months ago
I've recently started getting into c++ but I'm having trouble creating and using classes, when I try to run my program I get a few errors. This is my header file: MyClass.h #include <iostream> class MyClass { public: MyClass(); void setVar(int k); private: int x; }; ------------------------------------------ this is the actual class: MyClass.cpp #include "MyClass.h" MyClass::MyClass(){} void MyClass::setVar(int k) { x = k; } ------------------------------------------------- this is my program MyClassTest.cpp #include "MyClass.h" using namespace std; int main() { MyClass c; return 0; } When I run it I get a few errors, I'm running it on a solaris machine with the command g++ MyClassTest.cpp Is there something wrong with my implementation of these classes or the header?
Advertisement
It looks like you're only compiling one of the source files. You have to compile MyClass.cpp too. (I'm not familiar with g++ syntax; Linux classes were long ago :))
my_life:          nop          jmp my_life
[ Keep track of your TDD cycle using "The Death Star" ] [ Verge Video Editor Support Forums ] [ Principles of Verg-o-nomics ] [ "t00t-orials" ]
Complementing the post above:

g++ MyClassTest.cpp MyClass.cpp -o executable_name

BTW, there is the über usefulness of using both -Wall and -ansi arguments. First gives you warnings that could make your code crash and stuff -- better to take then into account; second is to make the compiler check everything according to ANSI C++ standards. So:

g++ main.cpp class.cpp -o test -Wall -ansi

Way to go.
Just for what it's worth, there's no reason to #include <iostream> from MyClass.h. :)

This topic is closed to new replies.

Advertisement