How to invoke function from external .c file in C?
My files are
// main.c
#include "add.c"
int main(void) {
int result = add(5,6);
printf("%d\n", result);
}
and
// add.c
int add(int a, int b) {
return a + b;
}
Solution 1:
Use double quotes #include "ClasseAusiliaria.c"
[Don't use angle brackets (< >
) ]
And I prefer to save the file with .h
extension In the same directory/folder.
TLDR:
Replace #include <ClasseAusiliaria.c>
with
#include "ClasseAusiliaria.c"
Solution 2:
Change your Main.c
like so
#include <stdlib.h>
#include <stdio.h>
#include "ClasseAusiliaria.h"
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
Create ClasseAusiliaria.h
like so
extern int addizione(int a, int b);
I then compiled and ran your code, I got an output of
11
Solution 3:
You must declare
int add(int a, int b);
(note to the semicolon)
in a header file and include the file into both files.
Including it into Main.c will tell compiler how the function should be called.
Including into the second file will allow you to check that declaration is valid (compiler would complain if declaration and implementation were not matched).
Then you must compile both *.c files into one project. Details are compiler-dependent.