undefined reference to Class::Function() C++

落爺英雄遲暮 提交于 2019-12-12 04:18:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!