Is it possible to use the Boost.DateTime library from C, and if so are there any examples available (preferably covering the build process using gcc-type tools)? I've searched the Boost documentation and the internet in general, and it seems theoretically possible, but have not found any clear answer one way or the other.
Boost.DateTime from C?
225 Views Asked by mwag AtThere are 2 best solutions below
On
C and C++ are highly interoperable; calling C code from C++ is trivial; calling C++ code from C however is more restricted because the interface must have C linkage and contain only types available in C and cannot use C++ specific features such as default arguments or function overloading for example.
To use C++ code in C requires that the interface has a extern "C" linkage specification, which is itself not valid C, so the specification in any header file must be conditional e.g.:
// interop.h
#if !defined INTEROP_H
#define INTEROP_H
#if defined __cplusplus
extern "C"
{
#endif
// C interface here
void somefunction() ;
#if defined __cplusplus
}
#endif
#endif // INTEROP_H
Then the implementation of the interface itself would be C++ code:
// interop.cpp
#include "interop.h"
void somefunction()
{
// C++ code here callable from C through somefunction()
}
But the interface is callable from C code:
// notcpp.c
#include "interop.h"
int main()
{
somefunction() ;
}
This approach is fine where the interface is simple, so for example if you use the Boost Date/Time library for some very specific procedure the results of which can be represented in C, then that might be appropriate if implementing equivalent functionality in C alone would be prohibitive. But creating C wrappers for entire C++ classes is time consuming error prone, inflexible and and ultimately pointless - it would be generally simpler to compile your C code as C++ then the interoperability barrier disappears as you can then introduce C++ specific code directly into your existing codebase (though it can never thereafter be compiled as C). C++ is multi-paradigm and includes the C library within its own C++ library, and most third-party and OS C library headers already include the C++ conditional C linkage wrapper, so you need not rewrite all your code in the OOP style in order to use C++ if you only want to take advantage of the larger library ecosystem.
No. Boost is a C++ library and Boost.DateTime is no exception. If you look at any of the DateTime headers you'll see C++ features everywhere, from classes to templates to namespaces and much more - none of which are supported in C.
You can, however, create a wrapper library in C++ which exposes the functionality you need as pure C functions, then call those from C.