[英]I'm getting “undefined reference” errors for a bunch of my functions and I can't figure out why
我班上的每個函數都給我這個錯誤。 我將以我的3參數構造函數為例:
#include <iostream>
using namespace std;
class Mixed{
public:
Mixed(int i, int n, int d);
private:
int integer, numerator, denominator;
};
和我的cpp:
#include "mixed.h"
#include <iostream>
#include <iomanip>
using namespace std;
Mixed::Mixed(int i, int n, int d){
int valid;
int negatives = 0;
if (d == 0){
valid = 0;
}
if (d < 0 | n < 0 | i < 0 && valid != 0){ //if there are any negatives and it hasn't been made invalid
if (i < 0){ //start counting negatives
negatives++;
}
if (n < 0){
negatives++;
}
if (d < 0){
negatives++;
}
if (negatives > 1){ //invalid if more than one negative value
valid = 0;
}
else {
valid = 1;
}
if (i != 0 && valid != 0){ //check for order if it hasn't already been made invalid
if (n < 0 | d < 0){ //invalid if integer is non zero, but one of the others is negative
valid = 0;
}
}
else if (n != 0 && d < 0){ //invalid if integer is zero, numerator is nonzero, and denominator is negative
valid = 0;
}
else if (valid != 0){ //if it hasn't already been invalidated, it's valid
valid = 1;
}
}
if (valid == 0){
this -> integer = 0;
this -> numerator = 0;
this -> denominator = 0;
}
else{
this -> integer = i;
this -> numerator = n;
this -> denominator = d;
}
}
使用我的課程的main.cpp確實包含
#include <iostream>
#include "mixed.h"
using namespace std;
我的錯誤如下所示:
/tmp/ccbdj59O.o:在函數main': main.cpp:(.text+0x34): undefined reference to
Mixed :: Mixed(int,int,int)的main': main.cpp:(.text+0x34): undefined reference to
我盡力了,這似乎是一個明顯的錯誤。 有什么想法嗎?
您要編譯兩個 cpp文件並將它們鏈接在一起。
可以通過以下命令使用g ++來完成
g++ mixed.cpp main.cpp -o output_file
這將編譯兩個文件並將它們鏈接在一起。 您也可以單獨執行以下操作:
g++ -c mixed.cpp -o mixed.o
g++ -c main.cpp -o main.o
g++ main.o mixed.o -o output_file
如果您不知道如何使用命令行,請在Linux上使用本教程(基於您遇到鏈接器錯誤並因此可以運行g ++的事實,我想是的)。 在Windows上,您可能需要使用IDE ,請在此處查找建議。
查看您的評論,您正在使用Sublime Text構建文件,也許嘗試打開工作文件夾(文件>打開文件夾...)而不是單個文件。 無論如何,我認為最好了解幕后發生的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.