I'm trying to include some functions written in C into a C++ project. I've come quite far following these instructions. Unfortunately not all of the C functions I require to call are declared in a c header file. Some are just static functions defined inside the ".c-files".
Is there a way to still call such "non-declared-C-functions" from inside a class of my C++ project without altering the C sources (which are not maintained by myself)?
I already thought about forward declaring the C function myself in my C++ header like this:
extern "C"
{
#include "c_header_1.h"
static void c_function(int* out, const unsigned char len, const some_c_struct* st);
#include "c_header_2.h
}
gcc only reports an error:
warning: void c_function(int*, const unsigned char, const some_c_struct*); declared static but never defined [-Wunused-function].
The pointer to struct passed as 3rd parameter to c_function(int*, const unsigned char, const some_c_struct*)
seems to make things even more tricky, since that type some_c_struct
is declared inside the header belonging to the ".c-file" c_function(...)
is declared in as well. This means I need to include the header before the forward declaration of c_function(...)
but apparently this makes the linker oversee the definition.
A very simplyfied version of the C++ code looks roughly this: Header File "CppClass.h":
#ifndef CPP_CLASS_H
#define CPP_CLASS_H
extern "C"
{
#include "c_header_1.h"
#include "c_header_2.h"
...
}
class CppClass
{
public:
//...
void some_member();
//...
};
#endif
Implementation "CppClass.cpp"
//...
void CppClass::some_member()
{
//...
::c_func_x(32, &data); // call to function in c_header_1
//...
::c_func_y(&data2); // call to function in c_header_2
::c_function(data3, len, st);
}
Clean answer: No. Functions declared static in a translation unit (.c or .cpp files typically) are not accessible anywhere else, even if you forward declare the correct function signature.
Messy answer, would not recommend: #include the offending .c file into your .cpp file and see if it works. I would consider this a hack though. Implementation files contain exactly what the name implies: implementations, not interfaces. This typically implies that you are not supposed to know about what is going on inside of it and that it might change between versions.
If you know the guy who is maintaining the sources, you could also try contacting him and ask if he could make the function part of the public interface, i.e. put it in a header and make it non-static.