"Undefined reference" error when compiling in C

I have a simple program where when compiling da an error

Undefined reference to'increment' /

main.c:

#include <stdio.h>
#include "incrementar.h"

int main()
{
    printf("Numero incrementado%d!", incrementar(10));
    return 0;
}


incrementar.h:

int incrementar(int i)
{
    return i++;
}



incrementar.c:

int incrementar(int i)
{
    return i++;
}

Note: I'm using Code:: Blocks.

Author: Maniero, 2017-09-23

2 answers

You need to compile the two codes:

gcc -o main main.c incrementar.c

If Code:: Blocks did not put it alone it probably created the project in the wrong way. It has to be with Project > Add Files.

 3
Author: Maniero, 2017-09-23 16:39:17

The structure of a TAD in code:: blocks is composed of the Sources folders where the files with extension.c should be stored and the Headers folder where the files .h should be stored.

insert the description of the image here

After checking the folders use the right button in each of the Files select the properties option, then go to the Build tab in the files with extension .C leave the compile file, link file, debug, and release options checked and for files with extension .h leave only the debug and release options checked. In this way the files belonged to the same project.

An error noticed in your code is that you implemented the increment function in two increment files.h and increment.c the correct would be to declare the function signature in the increment file.h and the implementation of the function would be done only in the increment file.c

Another error noticed in your code was return if you do return i++ the function will return the same value because the increment will be done after the display of the result the right would be return ++i. Follow the changes made in the code

Increment file.h

int incrementar(int i);

Increment file.c

#include "incrementar.h"
int incrementar(int i){

    return ++i;

}

Main file.c

#include <stdio.h>
#include <stdlib.h>
#include "incrementar.h"
int main()
{
   int valor,incremento;
   printf("Digite o valor a ser incrementado: ");
   scanf("%d",&valor);
   incremento = incrementar(valor);
   printf("Valor %d foi incrementado para %d",valor,incremento);
   return 0;
}
 1
Author: Ana Gomes, 2019-07-07 17:46:05