Undefined reference to class constructor, including .cpp file fixes

前端 未结 6 1622
萌比男神i
萌比男神i 2020-12-24 14:14

The problem I am having is that, when I call a constructor for a class I have created I get the following error.

main.cpp:20: undefined reference to

6条回答
  •  执念已碎
    2020-12-24 14:52

    The undefined reference error indicates that the definition of a function/method (i.e constructor here) was not found by the linker.

    StaticObject::StaticObject(Graphics*, sf::String,    sf::Vector2)
    

    And the reason that adding the following line:

    #include "GameObject/StaticObject.cpp"
    

    fixes the issue, is it brings in the implementation as part of the main.cpp whereas your actual implementation is in StaticObject.cpp. This is an incorrect way to fix this problem.

    I haven't used Netbeans much, but there should be an option to add all the .cpp files into a single project, so that Netbeans takes care of linking all the .o files into a single executable.

    If StaticObject.cpp is built into a library of its own (I highly doubt that is the case here), then you might have to specify the path to the location of this library, so that the linker can find the implementation.

    This is what ideally happens when you build your program:

    Compile: StaticObject.cpp -> StaticObject.o
    Compile: main.cpp -> main.o
    Link: StaticObject.o, main.o -> main_program
    

    Although there are ways in gcc/g++ to skip all the intermediate .o file generations and directly generate the main_program, if you specify all the source files (and any libraries) in the same command line.

提交回复
热议问题