Jose V
Jose V

Reputation: 1854

C compiling - 'undefined reference to function' when trying to link object files

so i create the object files with

cc -c MAIN.C
cc -c tablero.c

but then when i try to link them to an executable with

cc MAIN.o tablero.o

i get

undefined reference to `asdf()'

(function defined in tablero.c and called in MAIN.C)

here are my files:

i have MAIN.C

#include <stdio.h>
#include <cstring>
#include "tablero.h"
int main()
{
   int c;
   printf( "Enter a value :");
   c = getchar( );
   putchar(c);
   printf( "\nYou entered: ");
   c = asdf ();
   putchar(c);
   return 0;
}

i have tablero.h

#ifndef TABLERO_H_
#define TABLERO_H_
int asdf();
#endif // TABLERO_H_

and i have tablero.c

#include "tablero.h"
int asdf() {return 48;}; //48 is 0 in ascii

Upvotes: 10

Views: 4260

Answers (1)

zwol
zwol

Reputation: 140539

You have been bitten by an obscure feature of the cc tool on many Unixy systems: files whose suffix is lowercase .c are compiled as C, but files whose suffix is uppercase .C are compiled as C++! Therefore, your main (compiled as C++) contains an external reference to a mangled function name, asdf() (aka _Z4asdfv), but tablero.o (compiled as C) defines only an unmangled name, asdf.

This is also why you were able to include the C++ header file <cstring> in what was meant to be a C program.

Rename MAIN.C to main.c (and change <cstring> to <string.h>), recompile main.o, and your program should link.

If you actually want to compile part of your program as C and part as C++, then you can annotate your header files with extern "C" to make the symbols match up:

#ifndef TABLERO_H_
#define TABLERO_H_

#ifdef __cplusplus
extern "C" {
#endif

int asdf(void);

#ifdef __cplusplus
}
#endif

#endif // TABLERO_H_

Header files like this have to be extra careful to contain only code that has the same meaning in C and C++. Only POD types, no C++ keywords, no C99-but-not-C++ keywords either, no overloads, et cetera.

Upvotes: 22

Related Questions