【问题标题】:Using Multiple Files in C++ for functions and classes在 C++ 中为函数和类使用多个文件
【发布时间】:2013-12-12 06:22:30
【问题描述】:

我试图弄清楚如何制作一个由单独文件组成的程序。我读了这篇文章:

Function Implementation in Separate File

但是没有成功。我有 3 个文件:main.cpp、func.cpp、time.h,当我编译时,我收到以下错误消息:

duplicate symbol getOpen(std::basic_ofstream<char, std::char_traits<char> >&)in:
    /var/folders/kp/57zkm0tn1q7b7w0cs7tlf98c0000gn/T//cczaW1Px.o
    /var/folders/kp/57zkm0tn1q7b7w0cs7tlf98c0000gn/T//ccvOCRgc.o
ld: 1 duplicate symbol for architecture x86_64
collect2: ld returned 1 exit status

我不知道这意味着什么。我基本上只是想打开一个文件,写入它,然后关闭它。我也刚刚创建了一个对象并对其进行了测试。我知道问题出在 func.cpp 因为当我删除它时它可以工作。有人可以建议吗?谢谢。

我输入这个来编译:g++ main.cpp func.cpp

这是我的代码:

时间.h

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;

class Time
{
    private:
        int seconds;
        int minutes;
        int hours;
    public:
        Time(int=0, int=0, int=0);
        Time(long);
        void showTime();
};

Time::Time(int sec, int min, int hour)
{
    seconds = sec;
    minutes = min;
    hours = hour;
}

Time::Time(long sec)
{
    hours = int(sec / 3600);
    minutes = int((sec % 3600)/60);
    seconds = int( (sec%60) );
}

void Time::showTime()
{
    cout << setfill('0')
         << setw(2) << hours << ':'
         << setw(2) << minutes << ':'
         << setw(2) << seconds << endl;
}

func.cpp

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int getOpen(ofstream& fileOut)
{
    string filename = "outfile.txt";
    fileOut.open(filename.c_str());

    if( fileOut.fail())
    {
        cout << "\nFailed to open file.\n";
        exit(1);
    }
    else
        return 0;
}

main.cpp

#include <iostream>
#include "time.h"
#include "func.cpp"

int main()
{
    ofstream outFile;
    Time t1;

    t1.showTime();

    getOpen(outFile);

    outFile << "This is a test" << endl;

    outFile.close();

    return 0;
}

【问题讨论】:

  • 另外,通常在头文件中包含所有函数原型?
  • 是的。在您的情况下,它可能是“func.h”。并考虑在头文件中使用#ifdef 保护(以防止包含它们的内容两次)。

标签: c++ function class file-io include


【解决方案1】:

你不应该把#include "func.cpp" 变成main.cpp

嗯,这取决于你如何编译你的程序。如果你只编译 main.cpp,那么你应该包含 func.cpp。但这不是编写程序的好方法,我希望你不要那样做。

您可能想要做的是分别编译 main.cpp 和 func.cpp(使用 gcc -c),然后链接 .o 文件。如果您不将一个 .cpp 文件包含到另一个文件中,那将是完全可以的。但是,当您将 func.cpp 包含到 main.cpp 中时,两个 .o 文件都定义了 getOpen 函数。这会导致错误。

所以:只需删除 main 中的#include。

【讨论】:

  • 非常感谢!你能给我你要输入的命令来编译和链接吗?我只是在做g++ main.cpp func.cpp
【解决方案2】:

您将"func.cpp" 包含在main.cpp 中,因此您有一个getOpen 的双重声明。

【讨论】:

  • 这确实是标准做法——.h 文件中的原型,.cpp 文件中的定义(并在 .cpp 中包含标头)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 2021-08-25
  • 1970-01-01
相关资源
最近更新 更多