所以我正在为我的CompSci 2课做一些功课,并且遇到了几个障碍。我可以很好地编译NBAplayer.h,但编译client.cpp会产生:
client.cpp :(。text + 0x10a):未定义的引用 `NBAplayer :: setname可以(性病:: basic_string的, std :: allocator>)'
尝试编译NBAplayer.cpp会产生以下结果:
/usr/lib/gcc/i686-redhat-linux/4.5.1 /../../../ crt1.o:功能
_start': (.text+0x18): undefined reference to
主要'collect2:ld 返回1退出状态
这是我拥有的三个文件:
client.cpp
#include <iostream>
#include <string>
#include "NBAplayer.h"
using namespace std;
int main() {
struct NFLPlayer{
string name;
string currentTeam;
string Position;
string School;
};
bool playerCheck;
int playerType;
string playerName;
string playerTeam;
string playerPosition;
string playerSchool;
playerCheck = false;
NBAplayer player1;
while(playerCheck == false)
{
cout << "What kind of player would you like to create? (Enter 1 for NBA, 2 for NFL): "
<< endl;
cin >> playerType;
if(playerType = 1) {
}
else if(playerType = 2) {
cout << "Please enter your NBA Player's name: "
<< endl;
cin >> playerName;
player1.setName(playerName);
}
else {
cout << "Please check your input and try again!"
<< endl;
}
}
};
NBAplayer.h
#include <string>
class NBAplayer {
private:
std::string name;
std::string team;
char position;
std::string school;
public:
void setName(std::string playerName);
void setTeam(std::string teamName);
void setPosition(char playerPosition);
void setSchool(std::string schoolName);
std::string getName();
std::string getTeam();
char getPosition();
std::string getSchool();
};
NBAplayer.cpp
#include "NBAplayer.h"
#include <string>
void NBAplayer::setName(std::string playerName) {
name = playerName;
}
std::string NBAplayer::getName() {
return name;
}
void NBAplayer::setTeam(std::string teamName) {
team = teamName;
}
std::string NBAplayer::getTeam() {
return team;
}
void NBAplayer::setPosition(char playerPosition) {
position = playerPosition;
}
char NBAplayer::getPosition() {
return position;
}
void NBAplayer::setSchool(std::string schoolName) {
school = schoolName;
}
std::string NBAplayer::getSchool() {
return school;
}
我已经阅读了很多引用它的stackoverflow问题,但我感觉我做错了,因为我无法编译。如果您需要更多信息,请告诉我们!
答案 0 :(得分:3)
NBAPlayer.h
。-c
单独编译每个文件(编译,而不是链接),然后将生成的.o
文件一起编译来完成此操作。或者你可以一次给所有源文件g++
,这将要求它编译并将它们链接在一起。答案 1 :(得分:0)
1当您遇到错误undefined reference to
时,实际上,它不是编译错误而是链接器错误(编译过程包括编译,链接和加载)。如您所见,您会发现{ {1}},来自连接器。
当你编译client.cpp时,你得到
collect2: ld returned 1 exit status
因为你不能一起编译NBAplayer.cpp。链接器无法找到undefined reference to NBAplayer::setName(std::basic_string, std::allocator >)
的工具。
2当你编译NBAplayer.cpp时,你得到
NBAplayer::setName
那是因为你只想将NBAplayer.cpp编译成一个可执行对象,但每个cpp必须有一个主函数,而你没有一个,所以你得到了这个问题。
3你应该这样做:undefined reference to main
,编译它们。