Folks, Assuming I have a c++ application / library running which implements say
/* Alloc API */
void* my_alloc(int size) {
return malloc(sizeof(size));
}
This is not under "extern c".
I have a C dynamic library from which I need to call my_alloc, can I directly call that API?
Like,
int test_my_alloc (int size) {
int *x;
x = (int*)my_alloc(size);
if (x == NULL) {
return 0;
} else {
return 1;
}
}
You need to create a stub, e.g.
Stub header:
// stub.h
#ifdef __cplusplus
extern "C" {
#endif
void* my_alloc_c(int size);
#ifdef __cplusplus
}
#endif
Stub implementation:
// stub.cpp
#include "stub.h"
#include "header_where_my_alloc_is_declared.h"
void* my_alloc_c(int size)
{
return my_alloc(size);
}
Your C code (example):
// my_code.c
#include "stub.h"
int main()
{
void * p = my_alloc_c(42);
return 0;
}
Then compile your stub and link it with your C code:
g++ -Wall -c stub.cpp # compile stub.cpp
gcc -Wall my_code.c stub.o # compile your C code and link with stub.o
As Paul R. answered, you need a stub code. also, you'll better be sure that your C++ function does not throw exceptions (I guess that a C++ function, called from a C program and main, which throws an uncaught exception is having some undefined behavior). BTW, you should be sure that the constructor of static C++ data (like std::cout) is called "conceptually" before your main in C (so you better link your program with a C++ compiler, not a C one). See the GCC __attribute__(constructor)
In practice, at least on Linux with C++ code compiled by GCC (g++) or by Clang/LLVM (clang++), a C++ function has some mangled name.
You might use some ugly and non-portable trick to call a function by its mangled name. You could dare coding:
int main(int argc, char**argv) {
extern void* _Z10my_alloc_ci(int size);
void * p = _Z10my_alloc_ci(42);
return 0;
}
but I am a bit ashamed of giving such silly advice. You could even use asm labels e.g.
extern void*f(int) asm ("_Z10my_alloc_ci");
p = f(42);
However, I feel that you should not have any such approaches, and I am surprized why you need to call a C++ function which is not wrapped around extern "C".
Notice that in theory, C++ functions (without extern "C") could even have a different -and incompatible- calling convention than C functions. I don't know any implementation doing that. So to be safe you should wrap your C++ function with some C++ wrapping using extern "C"
To avoid uncaught exceptions, you might catch all of them in your C++ wrapper:
#include <cstdio>
#include <cstdlib>
extern "C" void* my_alloc_c(int size) {
extern void* my_alloc(int);
try {
return my_alloc(size);
} catch (...) {
::fprintf(::stderr, "got uncaught C++ exception for my_alloc(%d)\n",
size);
::fflush(nullptr);
::abort();
}
}
BTW, if your C++ library is large, you might perhaps try to automatize the generation of the glue code. For example, you could customize GCC using MELT (a Lispy domain specific language to extend GCC) by coding an extension in MELT which would generate the glue code when compiling the C++ header files.
You might be interested in libffi which enables you to (portably) call any (C and probably C++) function of arbitrary signature.
From what I gathered:
You have a C++ library you have no control over (you can't add the extern "C")
You have a C library that must call the C++ library
You can modify your C library to accommodate a solution (you can change the makefile and change the name of the function you want to call)
So, one alternative solution would be to compile your C library with the very same C++ compiler used for that C++ library, if that's acceptable for you.
Note: with C89, you'll possibly need to modify bits of your code (e.g. void * to T * conversions are not implicit anymore in C++), but it would probably be easier than 100+ wrappers.
Note 2: If you're using some C99 features (e.g. the VLAs), then that code will not compile in C++.
Related
My goal is to write a library which exposes only a public API in C language.
Let's say I'm writing a library, and it depends on two other libraries: a.c, and b.c
Contents of a.c:
int a(void) { return 1; }
Contents of b.c:
int b(void) { return 2; }
And let's say my library is m.c and its contents are:
#include "a.h"
#include "b.h"
int m(void) {
return a() + b();
}
My goal is to hide int a(void) and int b(void) so that they don't pollute the global namespace. I want the only symbol to be exported to be int m(void). That is, if my user defines their own a, they shouldn't get a link error:
#include "m.h"
int a(void) { // SOME OTHER FUNCTION
return 5;
}
int main(void) {
return m() + a();
// THIS WOULD CREATE A LINK ERROR,
// SINCE THERE ARE TWO `A` FUNCTIONS
// IN SYMBOL TABLE
}
The only thing that comes to mind is to define macros with the same name as a and b like this:
#define a internal_a
#define b internal_b
This would create name-mangled symbols, and once user has an executable, they can strip away internal dependency symbols using strip -s file.elf
Another way would be to design internal dependencies as UNIX style filter programs. However, this would require serialization, and would only work if all the internal dependencies belong to me.
Both methods are not ideal, so I'd like to see if there are any better ways to achieve this in C. I'm also not sure how C++ solves this. Most probably the symbols C++ exposes have names namespace-funcname-params.
edit: This would be trivial if I had all my dependencies in a single file. I'd simply use static keyword where needed. My question is specifically about multiple file libraries.
edit: Even though standard C doesn't provide a portable solution for this, the problem is still very common in programming. So, solutions might not be directly relevant with C, but more with the build tools (compiler, linker, preprocessor..)
So what I want to do is I want to create a kind of framework for myself in the future but I realized I can't do something. It goes like this:
void whenPressedQ();
void whenPressedW();
...
void checkPressQ(){
whenPressedQ();
printf("Q was pressed");
}
...
void whenPressedW(){
doThings();
}
Later I will define these functions and choose which of them to use.
Problem is I can't do this for the other functions if I haven't defined them below. I get an "undefined function" error. Is there any way I can solve this? I've tried using pointers to functions and check if it's null but it's the same thing.
You can pass pointers to callback functions, or wrap them in structures, then have the library pass back a pointer to a function that matches the signature later, even one that you will write in the future. This was how the first C++ compilers implemented virtual methods of objects.
If you just want the code to compile while you’re getting around to the unimplemented functions, you can create dummy stub functions to shut the linker up.
Update
Here are some examples of what I mean. Your question is somewhat ambiguous. If what you are asking is how you can declare functions that you intend to implement later, and still be able to compile the program, the answer is to provide stubs. Here’s a MCVE of your interface:
#include <stdio.h>
#include <stdlib.h>
/* In older versions of C, a declaration like void doThings() would turn
* type-checking of function arguments off, like for printf().
*/
void whenPressedQ(void);
void whenPressedW(void);
void doThings(void); // Added this declaration.
void checkPressQ()
{
whenPressedQ();
printf("Q was pressed.\n"); // Don't forget the newline!
}
void whenPressedW()
{
doThings();
}
// Stub implementations:
void whenPressedQ(void)
// FIXME: Print an error message and abort the program.
{
fflush(stdout); // Don't mix the streams!
fprintf( stderr, "Unimplemented function whenPressedQ() called.\n" );
exit(EXIT_FAILURE);
}
void doThings(void)
// Is nothing a thing?
{}
// Test driver:
int main(void)
{
whenPressedW();
whenPressedQ(); // fails;
// Not reached.
return EXIT_SUCCESS;
}
If you want to let the program dynamically select which function to call, that is more complicated, but you can do it with callbacks. Here’s a simple example.
#include <stdio.h>
#include <stdlib.h>
// This would ordinarily go in a .h file:
typedef const char*(*callback_t)(void); // The type of a callback function.
extern callback_t get_the_answer(void);
// This would ordinarily go in a .c file:
int main(void)
{
callback_t ask_the_question = get_the_answer();
printf( "The answer to life, the Universe and Everything is %s.\n",
ask_the_question()
);
return EXIT_SUCCESS;
}
// This would ordinarily go in another .c file:
static const char* the_answer_is(void)
{
return "42";
}
callback_t get_the_answer(void)
{
return &the_answer_is;
}
The error you are getting a linker error. If you are not trying to build an executable, then you can just compile and do not link. On Linux / OS X, you can pass the -c flag to clang or gcc. On Windows, you can pass the /c flag to cl.exe when compiling.
You can then link the object files directly later, or build a static or dynamic library out of them.
I am just a beginner in C++. I am trying to construct some header file header.h, but the output is always like the following:
/tmp/ccTmZKXX.o: In function `main':
main.c:(.text+0x13): undefined reference to `func'
collect2: ld returned 1 exit status
Could you please help me to see whether my way of using header file is correct or not? Thanks a lot!
Main code (main.c):
#include "stdio.h"
#include "func.h"
main() {
double a = f(2.3);
printf("a=%f\n", a);
}
where func.c contains:
double func (double x) { return x ;}
where func.h contains:
double func (double);
And I compile with:
gcc -o main main.c
There are multiple problems here:
The C++ compiler in the GCC (GNU Compiler Collection) is g++, not gcc; the latter is the GNU C Compiler.
The code in main.c is a (not very good) C program and not a C++ program. C99 outlawed the implicit int return type; C++ essentially never allowed it.
Your question uses a function f; your compilation error references func. This means you did not show us exactly the code you tried to compile.
The standards say #include <stdio.h>; you should too.
#include <stdio.h>
#include "func.h"
int main()
{
double a = func(2.3);
printf("a=%f\n", a);
}
NB: This is a perfectly good C program if you work with C99. In C89, you are expected to return a value from main() rather than 'fall off the end'. C99 follows C++98 and allows falling off the end as equivalent to an explicit return 0;. I tend to put the explicit return(0); (usually with, sometimes without, the parentheses - the compilers don't mind either way) anyway. (I compile C with -Wstrict-prototypes; to get a warning-free compilation, I write int main(void), which also works with C++ but the void is not necessary there.)
The header is OK, though you will learn in due course about header guards and other paraphernalia that make headers more reliable.
#ifndef FUNC_H_INCLUDED
#define FUNC_H_INCLUDED
extern double func(double a);
#endif /* FUNC_H_INCLUDED */
The extern is not mandatory. I tend to use it, but there are many who do not.
The source file defining the function should include the header to ensure that the function definition is consistent with the declaration. All code that uses the function should include the header so that there is a prototype in scope. This cross-checking is crucial for reliability. C++ requires prototypes in scope before a function is used; it does not demand a prototype in scope before the function is defined (but it is good practice to do so). It is strongly recommended in C that you have a prototype in scope before defining an external (non-static) function. You can use -Wmissing-prototypes with C code and GCC to spot such problems, but the option is not valid for G++.
#include "func.h"
double func(double x) { return x; }
Since this is a C++ question, we could consider inlining the function in the header. Indeed, C99 also supports inline functions. However, we can ignore that for the time being.
Since this is a C++ question, we could consider that using <stdio.h> is not good because it is not type safe. You might be better off using <iostream> et al, not least because they are type safe.
#include <iostream>
#include "func.h"
int main()
{
double a = func(2.3);
std::cout << "a=" << a << std::endl;
}
The correct compilation requires both the main program and the function it invokes, so you might write:
g++ -o main main.c func.c
Or, if you are compiling it in C, then:
gcc -std=c99 -o main main.c func.c
Note that the -std=c99 is necessary to ensure that the absence of return in main() is acceptable.
Note that there are several extensions in use for C++ source code, including .C, .cpp and .cxx, all of which are accepted by G++ (as well as .c).
There are several things wrong here.
Define the function as follows in func.h
extern double func(double);
When compiling, provide all source (c, cpp) files
gcc main.c func.c -o main
You should be good to go.
Compile like this:
gcc -o main main.c func.c
Then it will be fine.
In object-oriented languages (C++) you can execute code before main() by using a global object or a class static object and have their constructors run the code you want.
Is there any way to do this in C? I don't have any specific problem I'm trying to solve, I'm just curious. One thing this might be useful for is automatically initializing a library.
You can do it with __attribute__ ((constructor)). I've tested the following example with both gcc and clang. That being said, it's not part of the language.
#include <stdio.h>
void __attribute__ ((constructor)) premain()
{
printf("premain()\n");
}
int main(int argc, char *argv[])
{
printf("main()\n");
return 0;
}
It does the following:
$ ./test
premain()
main()
GCC documents it at: https://gcc.gnu.org/onlinedocs/gcc-8.3.0/gcc/Common-Function-Attributes.html#Common-Function-Attributes
There are ways using __attribute__ but those are very specific to your compiler and code that is written using these are not really portable. On the other hand, the C language does not provide any start-up modules/libraries.
In C, logically main() is the first function called by the OS. But before calling main(), the OS calls another function called start-up module to setup various environment variables, initialize (un-initialized) static variables, build a stack frame (activation record) and initialize the stack pointer to the start of the stack area and other tasks that have to be done before calling main().
Say if you are writing code for embedded systems where there is no-or-minimal OS to do the above mentioned work, then you should explore these options which are compiler dependent. Other than GCC, Turbo-C and Microsoft C compilers provides facilities to add code in a particular hardware machine (f.e. 8086 machines).
In other words, the start-up modules are not meant for the programmers.
With gcc, you can do so by using the constructor function attribute, e.g.
__attribute__ ((__constructor__))
void foo(void) {
...
}
This will invoke foo before main.
Note: This is probably not portable to other compilers.
You can initialize global variables but not call functions within these initializations.
If your compiler can compile cpp files you can add a file with a class that call in the costructor your initialization code. The class must be allocated statically. For example:
#include "ext.h"
class cext
{
public:
cext()
{
ExtInit();
}
~cext(){};
};
cext g_cext;
The ExtInit() function must be defined as extern "C" in file ext.h.
#ifdef __cplusplus
extern "C" {
#endif
void ExtInit (void);
#ifdef __cplusplus
}
#endif
I was wondering if there is a way of finding which function called the current function (at runtime) in C.
I know you could use __FUNCTION__ in gcc, but is there a way without using the C preprocessor?
Probably not.
Cheers
No, there isn't. C isn't a particularly introspective language - things like the name of a function (or pieces of your call stack) simply aren't available at runtime in any sane fashion.
If, for some reason, you are looking for a lot of work for very little benefit, then you can build your programs with debug symbols, and you can write stack-walking and debug symbol lookup code. Then you might be able to find this out on the fly. But be careful, because the symbols you'll see in the debug info will be decorated with type info if you've got any C++ involved.
You've tagged this post gcc, so the relevant details ARE available, however this falls into the 'not recommended' and 'not guaranteed to be the same between compiler versions' territory.
Assuming you have a function f() from which you want to know the caller.
Rename that function to f_func() and define a macro f() that prints __func__ and then calls f_func(). Example:
void
f_func()
{
do something;
}
#define f() \
do { \
printf("f called from %s\n", __func__); \
f_func(); \
} while (0)
void
a()
{
f();
}
void
b()
{
f();
}
int
main(int argc, char **argv)
{
a();
b();
return(0);
}
There's no way to get a function name in the runtime. The only way is the preprocessor but it's very limited in its capabilities.
In case you have debug information available, you could walk the stack and get the function names from the debugging information. This is, however, neither a robust nor a portable solution.
There are couple of GNU functions that allow you to get function addresses and names from backtrace - backtrace() and backtrace_symbols(), but you need to compile your binary with -rdynamic flag
NO
The short answer is NO
but with preprocessor it can be done like this
Getting the name of the calling function in C (using the preprocessor)
Assuming you have a function f() from which you want to know the caller only for debugging purpose.
Rename that function to f_func() and define a macro f() that calls a version of f that prints func and then calls f_func() when DEBUG is defined.
In the final release the information is removed by calling the real function f_func()
Example
#ifdef DEBUG
#define f(a,b,c) f_debug(a,b,c, __func__)
#else
#define f(a,b,c) f_func(a,b,c)
#endif
bool f_func(int par1, int par2, int par3)
{
do_somthing();
}
bool f_debug((int par1, int par2, int par3, const char calling_func_name[])
{
printf("f called from %s\n", calling_func_name);
f_func();
}
void a()
{
f();
}
void b()
{
f();
}
int main(int argc, char **argv)
{
a();
b();
return(0);
}
Result is:
when DEBUG is defined
f called from a
f called from b
Use the __func__ identifier. The standard (section 6.4.2.2) requires that it be present for precisely this purpose:
The identifier __func__ shall be implicitly declared by the translator as if, immediately following the opening brace of each function definition, the declaration
static const char __func__[] = "function-name";
appeared, where function-name is the name of the lexically-enclosing function.
As Steve Jessop notes in a comment, this isn't part of the preprocessor as such, but an intrinsic part of the compiler.
There may well be ways of finding out this name by walking the stack and looking at debugging symbols. Cute, but insane.