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

时间:2014-04-23 02:53:21

标签: 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

谢谢, 布鲁克斯拉迪

1 个答案:

答案 0 :(得分:1)

您的main.cpp包括main.hpp,其中包含LA.cpp,因此LA.cpp的内容正在为LA.cpp编译一次,main.cpp编译一次}}

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

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