Pergunta

I wanted to know how to make a structure visible in both - inside a library & in a external header. let me try to explain in the following code

I have a struct :

typedef struct{
int a;
int b;
}strt_1;

i want to create an instance of the same in the application and pass it to a library function and later update a & b variables inside, hence

application

int main()
{
    strt_1 a;
    foo(&a);
}

inside the library:

   int foo(strt_1 *a)
   {
      a->b = 0;
      a->a = 1;
   }

problem: if I create the definition of the struct in the library, when I retype the same in application, it shows as a redifinition(obviously). but if I type it in application, I wont be able to compile it as it says definition missing, Soo, how do I show the contents of the Struct to the external 3rd party library user, and also make it visible to the library compiler?

Foi útil?

Solução

You should put the structure and the typedef in a header file that comes with the library. Both the library and the applications using the library uses this header file. Structures and typedefs defined in header file do not cause multiple definition errors, only defining global variables or functions in both will do that.

Also, functions in the library should be prototyped in the header files of your library as well.

Outras dicas

One simple solution is already used in the standard includes.

You can try to encapsulate it with an #ifdef.

Something like

--- Header file ---

#ifndef LIBRARYHEADERFILE_INCLUDED
#define LIBRARYHEADERFILE_INCLUDED

typedef struct{
int a;
int b;
}strt_1;

int foo(strt_1 *a);
#endif

--- End header file ---

Then, on your main program and library, you #include the header file. And that's it. Both your new type and the function are now visible in every place, without fear of redefinition errors.

Put the typedef in a MyLibrary.h header file. Then #include "MyLibrary" in both your library source file, and the external code using the binary version of the library.

define structure in header file and include that header in c file before using structure.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top