gpt4 book ai didi

c++ - 同一行上的多个定义错误。 (C++)

转载 作者:太空宇宙 更新时间:2023-11-04 11:35:16 25 4
gpt4 key购买 nike

我有一个新的复杂问题。编译器提示我正在重新定义一个函数,但它说我声明它的第一个地方有重新声明的位置。一旦我将 cpp 文件包含在另一个文件中,问题就开始了。为了解决我的问题,我将它导出到一个 hpp 文件,但不知道有用。这是我的代码。

主要.cpp:

#include <iostream>
#include <string>
#include "main.hpp"

using namespace std;

int main(int argc, char *argv[])
{
//Deal with arguments and send them to the correct functions
if (argc >= 2){

string op = argv[1];
if (op == "-a" || op == "--automatic"){
if (argc >= 3){
string FName = argv[2];
bool dbgbool;
if (argc == 4){
string dbgstring = argv[3];
if (dbgstring == "debug"){
dbgbool = true;
}
}
Lexer(FName, dbgbool);
}
}
else{
cout << "Invalid Argument\n";
goto help;
}

return 0;
}
//Or, just write help and info
help:
cout << "\n";
cout << "bwc v0.0.1U-(Unstable)\n\n";
cout << "Usage: bwc <operation> [...]\n";
cout << "Operations:\n";
cout << " bwc {-a --automatic} <file(s)>\n";
cout << " bwc {-i --interactive}\n";
cout << " bwc {-c --error-codes}\n";
cout << "\n";
return 0;
}

LA.cpp:

#include<iostream>
#include<fstream>
#include<string>
#include<sstream>

using namespace std;

string Lexer(string FileN, bool dbg){ //This is the line of re-declaration.

//If debugging,this writes out put to the console
if (dbg == true)
cout << "Beginning Lexical Analysis...\n";

//Create new file stream and set it equal to the source file
ifstream Ifile (FileN.c_str());
//Test if the last step failed, if so, write an error to the console, and terminate the compiler
if (!Ifile.is_open()){
cout << "Unable to open file. Path to file may not exist, or the file name could be incorrect.\n";
cout << "Error Code: -1\n";
return NULL;}
//Create new stringstream, and set it equal to the source file
string IFStream;
Ifile >> IFStream;
//Close the source file
Ifile.close();

//If debugging,this writes out put to the console
if (dbg == true)
cout << "Source file sucessfully read.\n";

//Set out stream equal to the modified in stream
string OFStream = IFStream;
return OFStream;
}

最后,主.hpp:

#ifndef MAIN_HPP_INCLUDED
#define MAIN_HPP_INCLUDED

#include "LA.cpp"
extern string Lexer(string,bool);

#endif // MAIN_HPP_INCLUDED

谢谢,布鲁克斯雷迪

最佳答案

你的main.cpp包含main.hpp,其中包含LA.cpp,所以LA.cpp的内容LA.cpp 编译一次,为 main.cpp 编译一次。

.hpp 文件应仅包含声明 (string Lexer(string,bool);),而定义 (string Lexer(string,bool) {... }) 应该放在 .cpp 中

当你处理类方法时,你不会看到这种问题,因为编译器接受方法的定义。但是函数应该只在 .cpp 文件中定义。

关于c++ - 同一行上的多个定义错误。 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23233947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com