¿Cómo puedo definir una función C en un archivo y luego llamarla desde otro?


Digamos que defino una función en el archivo func1.c, y quiero llamarla desde el archivo call.c, ¿cómo lograría esto? Gracias de antemano!

Author: Sam H, 2010-11-25

2 answers

Pondrías una declaración para la función en el archivo func1.h, y añadirías #include "func1.h" en call.c. Entonces compilaría o enlazaría func1.c y call.c juntos (los detalles dependen de qué sistema C).

 30
Author: David Thornley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-24 21:32:10

Utilice una Declaración directa

Por ejemplo:

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

Hay una característica que le permite reutilizar estas declaraciones de reenvío llamadas Archivos de encabezado. Simplemente tome las declaraciones forward, colóquelas en el archivo de encabezado, luego use #include para agregarlas a cada archivo fuente C en el que haga referencia a las declaraciones forward.

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

Por supuesto, para poder compilar ambos archivos fuente, y por lo tanto toda la biblioteca o programa ejecutable, necesitará agregar el salida de ambos .c archivos a la línea de comandos del enlazador, o incluirlos en el mismo "proyecto" (dependiendo de su IDE/compilador).

Muchas personas sugieren que cree archivos de encabezado para todas sus declaraciones de reenvío, incluso si cree que no los necesitará. Cuando usted (u otras personas) vaya a modificar su código, y cambie la firma de las funciones, les ahorrará tiempo de tener que modificar todos los lugares donde la función está declarada hacia adelante. También puede ayudar a salvarte de algunos sutiles errores, o al menos errores confusos del compilador.

 12
Author: Merlyn Morgan-Graham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-24 21:56:28