私は基本的なプログラミングのクラスにいて、ファイルをリンクする方法を学んでいます。問題は、誰も修正できないようなエラーに遭遇したことです。私はすでに教授、学生アシスタント、キャンパス内のプログラミング支援ラボに行ったことがありますが、うまくいきません。
また、ここで複数の定義エラーに関連する少なくとも 10 の異なる投稿を検索しましたが、いずれの場合も次のいずれかです。
.cpp ファイルまたは
関数定義はヘッダー ファイル内にあります。
ご覧のとおり、ここではどちらのケースも当てはまりません (コードを読みやすくするために、すべてのコメントを削除しました)。
ヘッダファイル: square.h:
#ifndef SQUARE_H
#define SQUARE_H
class Square
{
private:
float side;
public:
void setSide(float);
float findArea();
float findPerimeter();
};
#endif
関数定義ファイル: square.cpp
#include "square.h"
#include <iostream>
#include <cstdlib>
using namespace std;
void Square::setSide(float length)
{
side = length;
}
float Square::findArea()
{
return side * side;
}
float Square::findPerimeter()
{
return 4 * side;
}
プログラム ファイル: test1.cpp
#include "square.h"
#include <iostream>
using namespace std;
int main()
{
Square box;
float size;
cout << "\n\nHow long is a side of this square?: ";
cin >> size;
box.setSide(size);
cout << "\n\nThe area of the square is " << box.findArea();
cout << "\n\nThe perimeter of the square is " << box.findPerimeter();
cout << endl << endl;
return 0;
}
そして最後に、コンパイルしようとするたびにエラーが発生します:
/tmp/ccVaTqTo.o: In function `Square::setSide(float)':
square.cpp:(.text+0x0): multiple definition of `Square::setSide(float)'
/tmp/cc4vruNq.o:test1.cpp:(.text+0x0): first defined here
/tmp/ccVaTqTo.o: In function `Square::findArea()':
square.cpp:(.text+0xe): multiple definition of `Square::findArea()'
/tmp/cc4vruNq.o:test1.cpp:(.text+0xe): first defined here
/tmp/ccVaTqTo.o: In function `Square::findPerimeter()':
square.cpp:(.text+0x20): multiple definition of `Square::findPerimeter()'
/tmp/cc4vruNq.o:test1.cpp:(.text+0x20): first defined here
collect2: ld returned 1 exit status
参考までにコンパイルコマンドg++ test1.cpp square.cpp -o testfile
メイクファイルを使用しても違いはないようです。まったく同じコンパイルエラーを見つめるだけです。2 つの異なるメイクファイルを使用してみました。
メイクファイル 1
square: test1.cpp square.cpp
g++ test1.cpp square.cpp -o square
メイクファイル 2
square: test1.o square.o
g++ test1.o square.o -o square
test1.o: test1.cpp
g++ -c test1.cpp
square.o: square.cpp
g++ -c square.cpp
今わかっているのは、これがある種のリンカ エラーであることだけですが、どうすればよいかわかりません。私が尋ねた人は皆、私のコードが正しいと言っています。しかし、明らかに何かが間違っています。
どんな助けでも大歓迎です。:D