skip to Main Content

I have problems with my Makefile.
I used the following structure to generate the .o files of each cpp file, but does not work (using c works without problems, I cant find what is the problem)

%.o : %.cpp %.h
    g++ -c -Wall $< -o $@

And the error while compiling is a function is declared in a separated h and cpp file and added to the main file. But when I try to generate de .o file of main.cpp marks error in the function.

The command I used to compile the main.cpp -> g++ -c main.cpp -o main.o

The error that gives me is:

main.cpp: In function ‘int main(int, char)’:
main.cpp:9:9: error: ‘number’ was not declared in this scope9 | number();

This is the compiler that I used for it:
g++ (Ubuntu 11.2.0-19ubuntu1) 11.2.0
Linux 5.15.0-40-generic

Please, anyone could explain me if I’m doing wrong of something is left

/*main.cpp*/
#include <iostream>
#include "numb.h"

using namespace std;

int main(int argc, char* argv[])
{
    cout<<"Run"<<endl;
    number();
    cout<<"end Run"<<endl;
    return 0;
}
/*end main.cpp*/

/*numb.cpp*/
#include <iostream>
#include "numb.h"

using namespace std;

int number()
{
    cout<<"Function"<<endl;

    return 117;
}
/*end numb.cpp*/

/*numb.h*/
#include <iostream>
#define NUMB_H
#ifndef NUMB_H

int number();

#endif
/*end numb.h*/

2

Answers


  1. When compiling specify both CPP files, because #include fixes compile errors, but does not fix linker errors

    g++ -c main.cpp numb.cpp ...
    

    As a rule, in header files nothing have to be outside the #define guards:

    /*numb.h*/
    #define NUMB_H
    #ifndef NUMB_H
    #include <iostream>
    
    Login or Signup to reply.
  2. You got the header guard in the wrong order.
    Instead of:

    #define NUMB_H
    #ifndef NUMB_H
    

    It is supposed to be:

    #ifndef NUMB_H
    #define NUMB_H
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search