简体   繁体   中英

Error when compiling with GCC

Every time I compile I get the following error message:

Undefined reference to ( function name )

Let's say I have three files: Main.c , printhello.h , printhello.c . Main.c calls function print_hello() , which returns "Hello World". The function is defined in printhello.c .

Now, here's the following code of printhello.h:

#ifndef PRINTHELLO_H 
#define PRINTHELLO_H

void print_hello();

#endif

I am sure this code is fine. I still don't know why is it giving me the error, though. Can you help me?

Undefined references are the linker errors. Are you compiling and linking all the source files? Since the main.c calls print_hello() , linker should see the definition of it.

gcc Main.c printhello.c -o a.out

The error is, I think, a linker error rather than a compiler error; it is trying to tell you that you've not provided all the functions that are needed to make a complete program.

You need to compile the program like this:

gcc -o printhello Main.c printhello.c

This assumes that your file Main.c is something like:

#include "printhello.h"

int main(void)
{
    print_hello();
    return 0;
}

and that your file printhello.c is something like:

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

void print_hello(void)
{
    puts("Hello World");
}

Your declaration in printhello.h should be:

void print_hello(void);

This explicitly says that the function takes no parameters. The declaration with the empty brackets means "there is a function print_hello() which returns no value and takes an indeterminate (but not variadic) list of arguments", which is quite different. In particular, you could call print_hello() with any number of arguments and the compiler could not reject the program.

Note that C++ treats the empty argument list the same as void print_hello(void); (so it would ensure that calls to print_hello() include no arguments), but C++ is not the same as C.

Another way to do it is to explicitly build object files for the printhello:

gcc -c printhello.c -o printhello.o
gcc -o Main main.c printhello.o

This has the added benefit of allowing other programs to use the print_hello method

It seems that the error is from the linker and not the compiler. You need to compile and link both the source files. I think what you are doing is simply including the header file in Main.c and you are not compiling the printhello.c

You need to:

gcc Main.c printhello.c -o myprog

or

construct the object files first

gcc -c printhello.c
gcc -c Main.c

then link them

gcc Main.o printhello.o

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM