繁体   English   中英

乘以定义的符号 (C++)

[英]Multiply defined symbols (C++)

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

我有以下文件

卡库文件

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

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

卡库文件

#include "StringParser.cpp"

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

字符串解析器

#include <string>
#include <vector>

someType splitAtChar(){
    ...
}

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

LNK2005 "class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,class std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > > __cdecl splitAtChar(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,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 中定义

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

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

卡库文件

#include "StringParser.h"

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

字符串解析器

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

someType splitAtChar(){
    ...
}

字符串解析器

#ifndef STRING_PARSER_H
#define STRING_PARSER_H

someType splitAtChar();

#endif

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

在你的 CardBase.cpp 中

#include "StringParser.cpp"

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM