I am trying to properly understand how to call C functions from another source file in C. I have a simple example that I am trying to get working. I have two functions, function1 and function2, which are contained in file.c. I am attempting to call function 2 from main.c bur receive the error "undefined reference to function 2".
main.c
#include <stdio.h>
#include <stdlib.h>
#include "file.h"
int main()
{
int result = function2(3);
printf("Result = %d ", result);
return 0;
}
file.c
int function1(int a) /* Function 1 definition */
{
int val = a*a;
return val;
}
int function2(int val) /* Function 2 definition */
{
return val +5;
}
file.h
#ifndef FILE_H_INCLUDED
#define FILE_H_INCLUDED
extern int function1(int a) ;
extern int function2(int val);
#endif // FILE_H_INCLUDED
(I know that function1 and function2 can be combined into one function but I want to understand why this example isn't working! - thanks)
Works fine with copy/paste of your code into main.c file.c file.h
Misc good advice not related to the problem:
Settings -> Compiler -> Compiler flags tab. Check the options corresponding to -Wall -Wextra and -pedantic-errors. If there is no C11 option, add one. See this.
As someone pointed out, you should always #include "file.h"
from file.c
Your source code is correct. What you are probably not doing is linking the two object files together to create an executable.
From the command line, compile both files into object files
cc -Wall -std=c11 -c main.c
Creates main.o
cc -Wall -std=c11 -c file.c
Creates file.o
Then link them
cc -o my-executable main.o file.o
Then you will have a runnable binary called my-executable
. If you have an IDE, there will be an equivalent way to do the above, but it will be IDE dependent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With