问题
After searching for a solution to this for about a half an hour I have made no progress. The errors are as follows:
s\My Workspace\Project\main.cpp - Line 7 - undefined reference to 'Sally::Sally()'
s\My Workspace\Project\main.cpp - Line 9 - undefined reference to 'Sally::printCrap()'
main.cpp
#include <iostream>
using namespace std;
#include "Sally.h"
int main()
{
Sally sallyObject;
sallyObject.printCrap();
}
Sally.h
#ifndef SALLY_H
#define SALLY_H
class Sally
{
public:
Sally();
void printCrap();
};
#endif // SALLY_H
Sally.cpp
#include "Sally.h"
#include <iostream>
using namespace std;
Sally::Sally(){
}
void Sally::printCrap(){
cout << "Did someone say steak?" << endl;
}
Thank you in advance!
回答1:
I know this is a pretty old question but maybe it could help someone.
So, when adding any additional files (headers, source, etc.) follow this (if using Eclipse or similar IDE):
New file -> File... -> C/C++ header (source, etc.) -> next, next -> give it a name and make sure it's in the same path with your project, then check "Add file to active project", in build target(s): check all -> Finish.
Hope it helps.
回答2:
Your linker doesn't find Sally.cpp. (Quick intro to linker)
To compile your code type:
g++ -o main main.cpp Sally.cpp
来源:https://stackoverflow.com/questions/34982333/undefined-reference-to-classfunction-c