Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在一个文件中定义一个C函数,然后从另一个文件调用它?_C_File_Function_Call - Fatal编程技术网

如何在一个文件中定义一个C函数,然后从另一个文件调用它?

如何在一个文件中定义一个C函数,然后从另一个文件调用它?,c,file,function,call,C,File,Function,Call,如果我在文件func1.c中定义了一个函数,并且我想从文件call.c中调用它。如何完成此任务?您可以在文件func1.h中添加函数声明,并在调用.c中添加#包括“func1.h”。然后您将编译或链接func1.c和call.c(详细信息取决于哪个c系统)。使用 例如: typedef struct { int SomeMemberValue; char* SomeOtherMemberValue; } SomeStruct; int SomeReferencedFunctio

如果我在文件
func1.c
中定义了一个函数,并且我想从文件
call.c
中调用它。如何完成此任务?

您可以在文件
func1.h
中添加函数声明,并在
调用.c
中添加
#包括“func1.h”
。然后您将编译或链接
func1.c
call.c
(详细信息取决于哪个c系统)。

使用

例如:

typedef struct
{
    int SomeMemberValue;
    char* SomeOtherMemberValue;
} SomeStruct;

int SomeReferencedFunction(int someValue, SomeStruct someStructValue);

int SomeFunction()
{
   SomeStruct s;
   s.SomeMemberValue = 12;
   s.SomeOtherMemberValue = "test string";

   return SomeReferencedFunction(5, s) > 12;
}
有一个特性允许您重用这些称为的转发声明。只需获取转发声明,将它们放在头文件中,然后使用
#include
将它们添加到引用转发声明的每个C源文件中

/* SomeFunction.c */

#include "SomeReferencedFunction.h"

int SomeFunction()
{
   SomeStruct s;
   s.SomeMemberValue = 12;
   s.SomeOtherMemberValue = "test string";

   return SomeReferencedFunction(5, s) > 12;
}

/* SomeReferencedFunction.h */

typedef SomeStruct
{
    int SomeMemberValue;
    char* SomeOtherMemberValue;
} SomeStruct;

int SomeReferencedFunction(int someValue, SomeStruct someStructValue);

/* SomeReferencedFunction.c */

/* Need to include SomeReferencedFunction.h, so we have the definition for SomeStruct */
#include "SomeReferencedFunction.h"

int SomeReferencedFunction(int someValue, SomeStruct someStructValue)
{
    if(someStructValue.SomeOtherMemberValue == NULL)
        return 0;

    return someValue * 12 + someStructValue.SomeMemberValue;
}
当然,为了能够编译这两个源文件,从而编译整个库或可执行程序,您需要将这两个.c文件的输出添加到链接器命令行,或者将它们包含在同一个“项目”中(取决于您的IDE/编译器)


许多人建议您为所有转发声明创建头文件,即使您认为不需要它们。当您(或其他人)修改代码并更改函数的签名时,这将节省他们修改所有函数前向声明位置的时间。它还可以帮助您避免一些微妙的错误,或者至少避免令人困惑的编译器错误。

感谢您的精彩解释:D@SamH:还要注意,您可以在同一个源文件中拥有转发声明和实际定义。它仍然有效。这有助于代码组织,因此不必按照使用顺序编写函数。当你有两个相互调用的函数时,它也很有用。哦,好吧,它就像Java中的接口一样,如果C可以像Java一样,那就更好了。你可能想看看C++/C#