“对PrintArgv的未定义引用”:为什么?

时间:2012-04-07 01:36:51

标签: c++ g++ undefined-reference

当我编译程序时,我得到三个“未定义的'PrintArgv(...)''错误引用。我搜索过,但找不到我收到这些错误的原因。这是我的代码:

    #include "tools.hpp"

enum ARG_T {COMMAND, SWITCH, ARGUMENT};
void ReadArgs(int, char**, ofstream&);
void PrintArgv(char*, ARG_T, ofstream&);


int main(int argc, char* argv[])
{
    ofstream fout;
    try{
        fout.open("P1Ford.txt", ios::out | ios::app);
    }
    catch(...)
    {
        //fatal("Could not open file P1Ford.txt");
        cout << "Could not open file P1Ford.txt" << "\n";
        return -1;
    }

    ReadArgs(argc, argv, fout);

    fout.close();
    return 0;
}

/*-----------------------------------------------------------------------------
This function takes the values passed in through the command line
then examines each one to determine if it is the command, a switch or
an argument. Then passes it to a function to print it to the file.
-----------------------------------------------------------------------------*/
void ReadArgs(int argc, char* argv[], ofstream& fout)
{
    for(int c=0; c<argc; ++c)
    {
        if(c == 0) PrintArgv(argv[c], COMMAND, fout);
        else if(strncmp(argv[c], "-", 1) == 0) PrintArgv(argv[c], SWITCH, fout);
        else if(strncmp(argv[c], ">", 1) == 0) ;
        else PrintArgv(argv[c], ARGUMENT, fout);
    }
}

/*-----------------------------------------------------------------------------
This function prints the argument in the correct format
Command <command>
   Switch <switch>
   Argument <agrument>
   Argument <argument>
-----------------------------------------------------------------------------*/
void PrintArgv(char* val, ARG_T type, ostream& fout)
{
    if(type == COMMAND) fout << "Command " << val << "\n";
    if(type == SWITCH) fout << "\t" << "Switch " << val << "\n";
    if(type == ARGUMENT) fout << "\t" << "Argument " << val << "\n";
}

函数ReadArgs是我收到错误的地方。每次拨打PrintArgv都会给我一个错误。我正在使用G ++ 4.6.1。

2 个答案:

答案 0 :(得分:5)

您的原型的参数类型为ofstream &,而您的标头的类型为ostream &。这意味着PrintArgv的实现实际上是在声明一个新功能。你可以调用你指定原型的那个,因为你无意中创建了一个新函数,而不是定义原始函数的主体。

答案 1 :(得分:1)

使用事实上使用的参数替换顶部的函数定义:

#include "tools.hpp"

enum ARG_T {COMMAND, SWITCH, ARGUMENT};

void ReadArgs(int argc, char* argv[], ofstream& fout)
void PrintArgv(char* val, ARG_T type, ostream& fout)