C++ Error: undefined reference to `main'

前端 未结 2 1684
深忆病人
深忆病人 2020-12-15 07:54

I\'m working on a simple class List, but when compiling the header and cpp file, I get the error: undefined reference to `main\'

What am I doing wrong, and how could

相关标签:
2条回答
  • 2020-12-15 08:16

    Undefined reference to main() means that your program lacks a main() function, which is mandatory for all C++ programs. Add this somewhere:

    int main()
    {
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-15 08:38

    You should be able to compile list.cpp, you can't link it unless you have a main program. (That might be a slight oversimplification.)

    The way to compile a source file without linking it depends on what compiler you're using. If you're using g++, the command would be:

    g++ -c list.cpp
    

    That will generate an object file containing the machine code for your class. Depending on your compiler and OS, it might be called list.o or list.obj.

    If you instead try:

    g++ list.cpp
    

    it will assume that you've defined a main function and try to generate an executable, resulting in the error you've seen (because you haven't defined a main function).

    At some point, of course, you'll need a program that uses your class. To do that, you'll need another .cpp source file that has a #include "list.h" and a main() function. You can compile that source file and link the resulting object together with the object generated from list.cpp to generate a working executable. With g++, you can do that in one step, for example:

    g++ list.cpp main.cpp -o main
    

    You have to have a main function somewhere. It doesn't necessarily have to be in list.cpp. And as a matter of style and code organization, it probably shouldn't be in list.cpp; you might want to be able to use that class from more than one main program.

    0 讨论(0)
提交回复
热议问题