【问题标题】:How can I define a C function in one file, then call it from another?如何在一个文件中定义 C 函数,然后从另一个文件中调用它?
【发布时间】:2011-05-15 09:02:45
【问题描述】:

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

【问题讨论】:

    标签: c file function call


    【解决方案1】:

    使用Forward Declaration

    例如:

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

    有一个功能可以让您重用这些前向声明,称为Header Files。只需将前向声明放在头文件中,然后使用#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
    • @Sam H:还请注意,您可以在同一个源文件中拥有前向声明和实际定义。它仍然可以工作。这有助于代码组织,因此您不必必须按照函数的使用顺序编写函数。当您有两个相互调用的函数时,它也很有帮助。
    【解决方案2】:

    您可以在文件func1.h 中声明函数,并在call.c 中添加#include "func1.h"。然后将func1.ccall.c 编译或链接在一起(具体取决于哪个C 系统)。

    【讨论】:

    • oh ok 类似 Java 的接口,如果 C 能像 Java 一样制作就更好了
    • 你可能想看看 C++/C#
    猜你喜欢
    • 2014-04-17
    • 2016-06-10
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多