I have a code which is compiled into a library (dll, static library and so). I want the user of this library to use some struct to pass some data as parameters for the library function. I thought about declaring the struct in the API header file.
Few notes:
For a structure definition that is to be used across more than one source file, you should definitely put it in a header file.
Header File is the file where all the headers name are mentioned that going to be used or consumed in the main code file. On other hand Library is the file where the implementation code of each header is written down which is mentioned in the Header file.
Header files define the following functions: Structures of certain files and subroutines. Type definition (typedef) synonyms for data types. System parameters or implementation characteristics. Constants and macros that are substituted during the C language preprocessing phase.
A header in the construction and engineering world is a beam over an opening that disperses the structural load to the outside of the opening to keep structural integrity. Otherwise, the load from the roof, floor, or whatever is above the opening can lead to stress that can cause cracks, shifting, or even worse.
If it's a regular/static library, the library and application should be compiled using the same compiler. There're a few reasons for this that I can think of:
You may, however, often use slightly different versions of the same compiler to compile the library and the application using it. Usually, it's OK. Sometimes there're changes that break the code, though.
You may implement some "initialization" function in that header file (declared as static inline
) that would ensure that types, type sizes, alignment and packing are the same as expected by the compiled library. The application using this library would have to call this function prior to using any other part of the library. If things aren't the same as expected, the function must fail and cause program termination, possibly with some good textual description of the failure. This won't solve completely the problem of having somewhat incompatible compilers, but it can prevent silent and mysterious malfunctions. Some things can be checked with the preprocessor's #if
and #ifdef
directives and cause compilation errors with #error
.
In addition, structure packing problems can be relieved by inserting explicit padding bytes into structure declarations and forcing tight packing (by e.g. using #pragma pack
, which is supported by many compilers). That way if type sizes are the same, it won't matter what the default packing is.
You can apply the same to DLLs as well, but you should really expect that the calling application has been compiled with a different compiler and not depend on the compilers being the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With