How to solve undefined reference in main function?

Solution 1:

After you comment, even if including the cpp files is a workaround, please do not do that!

You have two acceptable ways.

  1. define the method in the class itself in the include file

    Some IDE by default create an include file containing only the method declarations and put the definitions in an implementation cpp file. But the standard allow the definition to be inside the class definition, it is commonly used for small methods or templates (*)

    So your header could be:

     #ifndef PID_H
     #define PID_H
     class PID
     {
         float _kp,_ki,_kd,_error,_previous_error,_dt;
         public:
             void set_params(float kp, float ki, float kd,float error,float previous_error,float dt) {
                 _kp = kp;
                 _ki = ki;
                 _kd = kd;
                 _error = error;
                 _previous_error = previous_error;
                 _dt = dt;
             }
    
     };
    
     #endif
    
  2. add the pid.cpp file to the list of source files for your project.

    This part actually depends on your build tools. But your screenshot shows that you already compile app.cpp and main.cpp. You just have to process pid.cpp the same way.


For templates, the recommended way is to put all the implementation in the include file. Not doing so requires to consistently explicitely instanciate the template for all its future usages, which is not an option in a general library.