【问题标题】:Multiply defined symbols (C++)乘以定义的符号 (C++)
【发布时间】:2020-07-05 06:57:31
【问题描述】:

我是个新手,在我的 c++ 代码中遇到了一些非常奇怪的错误。据我所知,它们是由于多个包含错误造成的。

我有以下文件

CardBase.h

#include <string>
#include <vector>
#include <map>

class Class1 {
    string someString;
    vector<type> someVector;
    map<type,type> someMap;
    type someMethod (param);
}

CardBase.cpp

#include "StringParser.cpp"

someType Class1::someMethod (param){
    // Use splitAtChar()
}

StringParser.cpp

#include <string>
#include <vector>

someType splitAtChar(){
    ...
}

这会在 VS 代码中产生两个错误:

LNK2005 "类 std::vector,class std::allocator >,class std::allocator,class std::allocator > > __cdecl splitAtChar(class std::basic_string,class std::allocator >,char)" (?splitAtChar@@YA?AV?$vector@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V?$allocator@ V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@@std@@V?$basic_string@DU?$char_traits@D@std@@ V?$allocator@D@2@@2@D@Z) 已经在 CardBase.obj 中定义

找到一个或多个多重定义的符号

【问题讨论】:

标签: c++ multiple-inclusions


【解决方案1】:

是的,不要在另一个中包含一个 cpp 文件。使用头文件。

CardBase.cpp

#include "StringParser.h"

someType Class1::someMethod (param){
    // Use splitAtChar()
}

StringParser.cpp

#include "StringParser.h"
#include <string>
#include <vector>

someType splitAtChar(){
    ...
}

StringParser.h

#ifndef STRING_PARSER_H
#define STRING_PARSER_H

someType splitAtChar();

#endif

这是基本的东西,你的 C++ 书应该解释如何组织你的代码。

【讨论】:

    【解决方案2】:

    在您的 CardBase.cpp 中

    #include "StringParser.cpp"
    
    someType Class1::someMethod (param){
        // Use splitAtChar()
    }
    

    您正在包含一个 .cpp 文件。如果您另外编译它,那么您将定义 splitAtChar() 两次,因此会出现错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2012-09-05
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      相关资源
      最近更新 更多