How to invoke function from external .c file in C?

2020-02-20 06:44发布

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;
}

8条回答
Ridiculous、
2楼-- · 2020-02-20 07:11

you shouldn't include c-files in other c-files. Instead create a header file where the function is declared that you want to call. Like so: file ClasseAusiliaria.h:

int addizione(int a, int b); // this tells the compiler that there is a function defined and the linker will sort the right adress to call out.

In your Main.c file you can then include the newly created header file:

#include <stdlib.h>
#include <stdio.h>
#include <ClasseAusiliaria.h>

int main(void)
{
    int risultato;
    risultato = addizione(5,6);
    printf("%d\n",risultato);
}
查看更多
对你真心纯属浪费
3楼-- · 2020-02-20 07:12

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

查看更多
小情绪 Triste *
4楼-- · 2020-02-20 07:14
 write main.c like this - 
 caution : while linking both main.0 and ClasseAusiliaria.o should be 
 available to linker.

 #include <stdlib.h>
 #include <stdio.h>
 extern int addizione(int a, int b)

 int main(void)
 {
     int risultato;
     risultato = addizione(5,6);
     printf("%d\n",risultato);
 }
查看更多
欢心
5楼-- · 2020-02-20 07:17

make a file classAusiliaria.h and in there provide your method signatures.

Now instead of including the .c file include this .h file.

查看更多
Emotional °昔
6楼-- · 2020-02-20 07:24

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
查看更多
孤傲高冷的网名
7楼-- · 2020-02-20 07:24

You can include the .c files, no problem with it logically, but according to the standard to hide the implementation of the function but to provide the binaries, headers and source files techniques are used, where the headers are used to define the function signatures where as the source files have the implementation. When you sell your project to outside you just ship the headers and binaries(libs and dlls) so that you hide the main logic behind your function implementation.

Here the problem is you have to use "" instead of <> as you are including a file which is located inside the same directory to the file where the inclusion happens. It is common to both .c and .h files

查看更多
登录 后发表回答