1

私は基本的なプログラミングのクラスにいて、ファイルをリンクする方法を学んでいます。問題は、誰も修正できないようなエラーに遭遇したことです。私はすでに教授、学生アシスタント、キャンパス内のプログラミング支援ラボに行ったことがありますが、うまくいきません。

また、ここで複数の定義エラーに関連する少なくとも 10 の異なる投稿を検索しましたが、いずれの場合も次のいずれかです。

  1. .cpp ファイルまたは

  2. 関数定義はヘッダー ファイル内にあります。

ご覧のとおり、ここではどちらのケースも当てはまりません (コードを読みやすくするために、すべてのコメントを削除しました)。

ヘッダファイル: 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

4

2 に答える 2

4

わかった。新しいクリーンなディレクトリを作成し、コードをコピーして新しいファイルに貼り付けます (古いファイルと同じファイル名を使用して、最終的にコンパイルすることができました。何らかの理由で、コンパイラは私の古いファイルを気に入らなかったと思います。

于 2013-10-31T13:08:20.900 に答える
0

たぶんこれが役立つと思います

次のようにメイクファイルを試してください。

square: test1.o square.o
        g++ test1.o square.o -o square

test1.o: test1.cpp square.h
        g++ -c test1.cpp

square.o: square.cpp square.h
        g++ -c square.cpp

編集 うまくいかない場合は、前処理のみを実行してみてください:

g++ -E test1.cpp

g++ -E square.cpp

出力をチェックして、正しいファイルが取得されたかどうかを確認します

于 2013-10-30T23:58:06.607 に答える