[英]Can't compile C++ code - “undefined reference to--”
所以我正在為CompSci 2類做一些作業,遇到了一些麻煩。 我可以很好地編譯NBAplayer.h,但是編譯client.cpp會產生:
client.cpp :(。text + 0x10a):對`NBAplayer :: setName(std :: basic_string,std :: allocator>)的未定義引用
並嘗試編譯NBAplayer.cpp會產生以下結果:
/usr/lib/gcc/i686-redhat-linux/4.5.1/../../../crt1.o:在函數
_start': (.text+0x18): undefined reference to
.text_start': (.text+0x18): undefined reference to
main'collect2的_start': (.text+0x18): undefined reference to
: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問題,但是由於無法編譯,我感到自己做錯了什么。 如果您需要更多信息,請告訴我!
NBAPlayer.h
。 -c
(編譯而不是鏈接)分別編譯每個文件,然后將生成的.o
文件一起編譯來完成此操作。 或者,您可以一次給g++
所有源文件,這將要求它編譯並將它們鏈接在一起。 1,當遇到錯誤的undefined reference to
,實際上,這不是編譯器錯誤,而是鏈接器錯誤(編譯過程包括complie,link和load)。如您所見,您將發現collect2: ld returned 1 exit status
,這來自鏈接器。
當您編譯client.cpp時,您會得到
undefined reference to NBAplayer::setName(std::basic_string, std::allocator >)
因為您沒有一起編譯NBAplayer.cpp。鏈接器找不到NBAplayer::setName
的實現。
2當編譯NBAplayer.cpp時,您得到
undefined reference to main
那是因為您只想將NBAplayer.cpp編譯為一個可執行對象,但是每個cpp必須具有一個主函數,而您卻沒有一個主函數,因此就遇到了這個問題。
3您應該這樣做: g++ client.cpp NBAplayer.cpp -o main
,同時編譯它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.