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 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 this, I just need to:

file2.c

#include "../file1.h"

This is enough? Probably not.

After that, when I compile file2.c, I getundefined reference to 'mine'

+5
source share
3 answers

You will also need to associate the object file with file 1. Example:

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

Or you can also combine all the files at once and let GCC do the work (not offered outside of multiple files);

gcc -o program file1.c file2.c
+6
source

Do not use ../ in the header. Instead, instruct gcc to use the parent directory as the include path:

( ):

gcc -I../ -c file2.c 
+1

, file2.c, undefined ""

, . , . , "".

" " - , , #include - , , . , , , ( ). , , , .

+1

All Articles