Skip to content

Instantly share code, notes, and snippets.

@aybabtme
Created July 19, 2012 16:26
Show Gist options
  • Save aybabtme/3145102 to your computer and use it in GitHub Desktop.
Save aybabtme/3145102 to your computer and use it in GitHub Desktop.
Learning C++ : classes/headers. Doesn't work, and I don't get why.
#include "BagOfValues.h"
BagOfValues::BagOfValues() {
mName = "Jake";
mWeight = 71.8;
mAge = 26;
}
#ifndef GUARD_BagOfValues_h
#define GUARD_BagOfValues_h
#include <string>
class BagOfValues {
public :
BagOfValues();
std::string getName() { return mName; }
double getWeight() { return mWeight; }
int getAge() { return mAge; }
private :
std::string mName;
double mWeight;
int mAge;
};
#endif
# THIS IS WRONG
$ clang++ Test.cpp
/tmp/Test-c7XlKn.o:Test.cpp:function main: error: undefined reference to 'BagOfValues::BagOfValues()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
# / THIS IS WRONG
# THIS IS RIGHT
$ clang++ -c Test.cpp
$ clang++ -c BagOfValues.cpp
$ clang++ Test.o BagOfValues.o
$ ./a.out
My name is Jake
My age is 26
My weight is 71.8
# / THIS IS RIGHT
#include "BagOfValues.h"
#include <iostream>
#include <string>
using std::cout;
using std::endl;
int main(){
BagOfValues *aBag = new BagOfValues;
cout << "Your name is " << aBag->getName() << endl;
cout << "Your age is " << aBag->getAge() << endl;
cout << "Your weight is " << aBag->getWeight() << endl;
return 0;
}
@aybabtme
Copy link
Author

Using this code, I get a compile error. I don't get why, and I think I just don't understand how the header files work with the classes.

@aybabtme
Copy link
Author

Got it! The code was just fine, the problem was in the linking.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment