"Undefined Reference" error when compiling in C

Asked

Viewed 3,980 times

2

I have a simple program where when compiling 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 am using Code::Blocks.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

2 answers

3

You need to compile the two codes:

gcc -o main main.c incrementar.c

If Code::Blocks didn’t put it up itself it probably created the project wrong. It has to be with Project > Add Files.

  • I have to compile both codes at the same time ? And this ?

  • Not necessarily, but the simplest way is this.

1

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 files . h should be stored.

inserir a descrição da imagem aqui

After checking the folders use the right button on each of the files select the properties option, then go to the Build tab on the files with extension. c leave the options Compile file, link file, debug and release marked and for the files with extension. h only leave debug and release options marked. This way the files belonged to the same project.

A noted error in your code is that you have implemented the increment function in two files increment. h and increment. c the correct one would be to declare the function signature in the increment file. h and the function implementation would be done only in the increment file. c

Another error noted 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 one 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.