【问题标题】:C++ class in separate file not compiling. Already defined in Class.obj one or more multiply defined symbols found单独文件中的 C++ 类未编译。已在 Class.obj 中定义 找到一个或多个多重定义符号
【发布时间】:2016-09-17 03:26:55
【问题描述】:

因此,我在 StackOverflow 上进行了广泛的谷歌搜索和搜索,尽管针对这个确切问题有多个答案,但我无法找到解决方案。

我正在尝试在名为 Fpc5.cpp 的外部文件中创建一个测试类

它的内容是:

Fpc5.cpp

#include "stdafx.h"
#include "Fpc5.h";
#include <iostream>
using std::cout;

class Fpc5 {
    int bar;
public:
    void testMethod();
};

void Fpc5::testMethod() {
    cout << "Hey it worked! ";
}

还有我的主 .cpp 文件:

Test.cpp

// Test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
//#include "Fpc5.cpp"
#include "Fpc5.h";
using std::cout;
using std::cin;
using std::endl;

int main()
{
    cout << "Hello" << endl;
    Fpc5 testObj;
    testObj.testMethod();

    system("pause");
    return 0;
}

我读过的所有答案都表明这是因为我曾经将类包含在主文件本身中,这就是我创建头文件的原因

Fpc5.h

#pragma once
void testMethod();

这改变了错误,但仍然没有解决问题。目前我的Test.cpp 无法识别 Fpc5 类。我还尝试在stdafx.h 中添加Fpc5.cppFpc5.h,但这仍然不能解决问题。

stdafx.h

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

// TODO: reference additional headers your program requires here

//#include "Fpc5.cpp"
#include "Fpc5.h"

我确定这是一个简单的语法/概念理解错误,但我对 c++ 很陌生,不确定哪里出了问题。

【问题讨论】:

  • 你的类定义需要在头文件中,而不是源文件中。

标签: c++ file class oop compiler-errors


【解决方案1】:

这是你的类的定义,它必须在 Fpc5.h 中

class Fpc5 {
    int bar;
public:
    void testMethod();
};

然后,您有 Fpc5.cpp,您可以在其中实现类的方法:

#include "Fpc5.h" // Compiler needs class definition to compile this file!

void Fpc5::testMethod()
{
}

然后你就可以在Test.cpp中使用Fpc5类了

#include "Fpc5.h"

int main()
{
    Fpc5 foo;
    foo.testMethod();
    return 0;
}

作为替代方案,您可以将所有内容打包到 Test.cpp 中

【讨论】:

  • 这确实允许我的 Test.cpp 识别 Fpc5 对象,但现在当我尝试编译时出现 2 个错误:“function_main 中引用的未解析外部符号 [...]”和“1 未解析” externals" 对这些有什么想法吗?
  • 我只需要清理和重建我的解决方案。感谢您的快速回答。
【解决方案2】:

移动你的类的定义:

class Fpc5 {
    int bar;
public:
    void testMethod();
};

到头文件“Fpc5.h”。

实现“Fpc5.cpp”的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多