Using function and header file (header)

Asked

Viewed 694 times

2

I am making a simple program but using header file . h (header) and a hello world function, but I have the following warning message: Undefined Reference to 'imprime'. I asked someone else to test it and said it worked out which might still be?

Follows code:

=== Arquivo MainCodeCount.c ==

#include <stdio.h>
#include <stdlib.h>
#include "LibCodeCount.h"

int main(int argc, char *argv[])
{
    imprime();

    return 0;
}


=== Arquivo CodeCount.c ===

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

void imprime()
{
    printf("Ola mundo!\n");
}


=== Arquivo CodeCount.h (header) ==

void imprime();
  • Thank you, gentlemen, but I decided as follows: I just configured gcc in the windows path and the commands: gcc -c Maincodecount. c gcc -c Libcodecount. c ; gcc -o HELLO Maincodecount. o Libcodecount. o .

  • If you solved your problem that way, better put as a reply instead of a comment. So it’s easier to know what Voc6e did to solve your problem.

3 answers

3


The problem is merely that you have compiled only one file, the MainCodeCount.c and left the CodeCount.c from outside. So there is no one defining the function the function imprime() in the linking step and the error occurs:

Undefined Reference to imprime()

The fix is to compile all your files:

gcc -c MainCodeCount.c                            (MainCodeCount.c -> MainCodeCount.o)
gcc -c LibCodeCount.c                             (LibCodeCount.c -> LibCodeCount.o)
gcc -o Hello MainCodeCount.o LibCodeCount.o       (*.o -> Hello.exe)

Another thing missing from your code but the way it is won’t cause you any trouble are the header Guards. In every header file use the following:

#ifndef MYHEADER_H
#define MYHEADER_H

// seu código aqui

#endif

Or:

#pragma once

// seu código aqui

The goal is for the header to be processed only once per build unit, even if included more than once.

0

Try referencing in all files

#include "CodeCount.h"

-2

Try Codecount. h, change the code to:

#ifndef __CODECOUNT_H__
#define __CODECOUNT_H__

void imprime();

#endif

In theory your error message has nothing to do with duplicate references, but I’m running out of other ideas of what it might be now.

  • 1

    Sorry, , but it’s Libcodecount. c and . h

  • No problem. If possible, edit the question to show the right file name.

  • I edited the answer with another possible solution.

Browser other questions tagged

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