Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a function in different .c files (c programming 101)

/me/home/file1.c containes function definition:

int mine(int i)
{
    /* some stupidity by me */
}

I've declared this function in

/me/home/file1.h

int mine(int);

if I want to use this function mine() in /me/home/at/file2.c

To do so, all I need to do is:

file2.c

#include "../file1.h"

Is that enough? Probably not.

After doing this much, when I compile file2.c, I get undefined reference to 'mine'

like image 264
hari Avatar asked Aug 16 '11 22:08

hari


People also ask

How do you call a function from another file in main C?

The usual way to call a 'C' function defined in another file without a common header file is to declare it as extern .

Can you include .C files in C?

You can properly include . C or . CPP files into other source files.


1 Answers

You will also need to link the object file from file1. Example:

gcc -c file2.c
gcc -c ../file1.c
gcc -o program file2.o file1.o

Or you can also feed all files simultaneously and let GCC do the work (not suggested beyond a handful of files);

gcc -o program file1.c file2.c
like image 108
Yann Ramin Avatar answered Oct 02 '22 07:10

Yann Ramin