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

标签 c++

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

main.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;
}

最后, main.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/

相关文章:

c++ - qDebug 将 QString UTF-8 非 Ascii 符号输出为 like\uxxxx

c++ - 与 Hudson 的持续集成和自动化测试 QWidgets

c++ - 为什么我不能将 boost::function 存储在 std::list 中?

c++ - CWinApp CFrameWindow 未显示

c++ - 我可以向不同的线程发送信号吗

c++ - 如何在多集中打印值?

c++ - 实时应用程序(游戏、模拟器等)的相关 C++ 编程书籍

c++ - 在 Mac OSX 中替代 --no-undefined

c++ - 在 python 线程中调用 TBB 'parallel_for'

c++ - gcc:链接外部库