user4134614
user4134614

Reputation:

header file (.text+0x15): undefined reference to

I write simple header file when I compile I get the error

/tmp/ccOH3HcX.o: In function `main':
sample.c:(.text+0x15): undefined reference to `f'
collect2: error: ld returned 1 exit status

whatever.h

#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif

Example whatever.c

#include "whatever.h"

int f(int a) { return a + 1; }

sample.c

#include "whatever.h"

int main(int argc, char **argv)
{
    printf("%d\n", f(2)); /* prints 3 */
    return 0;
}

To compile it :

$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o

Upvotes: 0

Views: 2437

Answers (2)

dddsnn
dddsnn

Reputation: 2481

The compiler steps you gave only create object files, not an executable. I suppose you did something like

gcc sample.c -o sample

afterwards and then got the error?

You have to link the object files to get an executable, like so:

gcc whatever.o sample.o -o executable_file

Upvotes: 2

warzon
warzon

Reputation: 187

You need to include the object file whatever.o on the second gcc compilation line.

A simple gcc whatever.c sample.c -o sample should do it

Upvotes: 2

Related Questions