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
Related
In my application I have a build config for pseudo unit testing (this is more a kind of manual debugging a dedicated function).
In those unit tests I'd like to access functions declared as static in their translation unit.
Is there an option of GCC that would allow me to call static functions from anywhere?
I'd like to avoid:
#if UNIT_TEST_MODE
void myfunction(void)
#else
static void myfunction(void)
#end
{
// body
}
Everywhere!
Thanks for your help :).
There is not need to be verbose. Use a prefix define for every static function:
#if UNIT_TEST_MODE
#define UNIT_TEST_STATIC
#else
#define UNIT_TEST_STATIC static
#end
UNIT_TEST_STATIC void myfunction(void)
{
// body
}
Another option is to move all static function from that .c file to a separate header. That header is included only in that .c file, but it can be included in the unit test .c file if needed. The functions will remain invisible in other files, unless the header is manually included.
(They will have to be defined as static inline. )
As applied to a function or file-scope variable, the static keyword means that the declared function or object has internal linkage. That means such a function or object can be directly referenced only from within the same translation unit. GCC has no option to alter this core provision of the C language, nor should it have.
Your alternatives, then, are either
to give the functions in question external linkage instead of internal linkage, perhaps conditionally, or
to make them available to the test code via an indirect mechanism, such as function pointers initialized and provided to the test code by some facility (another function, a global variable) inside the translation unit.
The first alternative is simpler, but using it means that the code under test is not wholly equivalent to code built for ordinary use. Additionally, this option is not viable if the names of any of the erstwhile-static functions collide with the names of other global objects. This option has been adequately demonstrated in other answers, so I won't go into further detail here.
The pros and cons of the second alternative are more or less the mirror image of those of the first. It is more complicated, but the functions can be tested in the same form that they have in the production build, and you can avoid name collisions by this route. There are many possible variations on this approach; here's one:
test_header.h
#ifndef TEST_HEADER_H
#define TEST_HEADER_H
struct test_pointers {
int (*function_to_test)(const char *);
};
void initialize_test_pointers(struct test_pointers *pointers);
#endif
module_under_test.c
static int function_to_test(const char *);
#ifdef ENABLE_TESTING
#include "test_header.h"
extern void initialize_test_pointers(struct test_pointers *pointers) {
pointers->function_to_test = function_to_test;
}
#endif
static int function_to_test(const char *s) {
// ... whatever
}
the_test.c
#include "test_header.h"
int test_it(void) {
struct test_pointers pointers;
char test_input[] = "test THIS!";
const int expected_result = 42;
int result;
initialize_test_pointers(&pointers);
result = pointers.function_to_test(test_input);
return result == expected_result;
}
No, it can not. This keyword specifies visibility of a function to be translation-unit only, as defined by launguage standard. Ignoring it by a compiler would render it non-conformant.
UPD. To solve your problem, you can indeed do the preprocessor directive trick, as mentioned in comments to your question.
This does not answer your question about GCC, but as a solution to your unit testing problem, you could conditionally compile a wrapper function in the same module,
static void myfunction(void)
{
// body
}
#if UNIT_TEST_MODE
void myfunction_test(void)
{
myfunction();
}
#endif
Or, you could #include the module from a unit test wrapper file,
// unit_test.c
#include "myfunction.c"
void unit_test()
{
myfunction();
}
I have a problem when using WEAK reference in C. Make assumption, I have the src code structure as follows:
//Eclipse C project structure
drv
| dummy
| | dummy_Test.h
| | dummy_TestWeakAttribute.h
| src
| | source_sample.c
| test
| | myModules
| strong_test_case.c
| weak_test_case.c
test_program.c
And:
//test_program.c
#include "drv/dummy/dummy_TestWeakAttribute.h"
#include "drv/dummy/dummy_Test.h"
int main() {
printf("===================\n");
printf(" Welcome to main \n");
printf("===================\n");
// Expectation
test(); //-->real function
function(); //-->real function
test_function_strong(); //-->real function
test_function_weak(); //-->weak function
return 0;
}
//source_sample.c
#include "../dummy/dummy_TestWeakAttribute.h"
#include "../dummy/dummy_Test.h"
static void test(void) {
printf("NOT overridden!\n");
}
static void function(void){
int a =1;
a++;
test();
}
//dummy_Test.h
#ifndef DRV_DUMMY_DUMMY_TEST_H_
#define DRV_DUMMY_DUMMY_TEST_H_
#define static
//definitions
//struct definitions
//dummy functions
static void test(void);
static void function(void);
//global variable definitions
#endif /* DRV_DUMMY_DUMMY_TEST_H_ */
//dummy_TestWeakAttribute.h
#define static //disable static keyword
static void __attribute__((weak)) test(void);
//weak_test_case.c
#include "../../dummy/dummy_TestWeakAttribute.h"
#include "../../dummy/dummy_Test.h"
static void test(void){
printf("overridden successfully!\n");
}
void test_function_weak(void){
function();
}
//strong_test_case.c
#include "../../dummy/dummy_Test.h"
void test_function_strong(void){
function();
}
I got the result on the screen:
===================
Welcome to main
===================
overridden successfully!
overridden successfully!
overridden successfully!
overridden successfully!
I can't use the REAL function anymore. All my making calls to the real test function is impossible because it was declared as __attribute__((weak)) before. So, Is there anybody having idea on this case ? The main purpose, I'd like to call my real test (in source_sample.c) but don't remove weak attribute as well.
First off, be aware that weak linkage is not a C concept. It is an ELF concept, at least for our purposes, and GCC (and other compiler) support for it is a C extension. Therefore, little of what I have to say is based on the C standard. With that said ...
Your program has two functions test(), both with weak linkage. If there were an alternative with strong linkage then that would override both. Since there is not, it is unspecified which of the two is linked to any given reference (call), but it follows from the mechanism of ELF dynamic linking that the same one would would be linked to every reference in any given dynamic object.
Other than system libraries, you have only one dynamic object in play -- the program -- so it stands to reason that the same implementation of test() is called at every point. It's unclear to me why you suppose it would be otherwise. Note in particular that the weird games you are playing with the static keyword are strictly obfuscatory. You have no actual static declarations anywhere in the code you present.
You indeed could declare a static function test in some file, and in that case you would expect calls to test() from within that file to be linked to the internal static version. To the best of my knowledge, however, a static function cannot also be weak. That wouldn't make any sense.
The main purpose, I'd like to call my real test (in source_sample.c) but don't remove weak attribute as well.
So you want to provide for overriding some references to the function but not others? Are you nuts? What a nightmare that would be to build, and I don't even want to think about maintaining it.
If you want to provide a default implementation that you can always call then you cannot make that the weak function. Doing so is inconsistent with always being able to call it. You can, however, make it a separate, ordinary function that the weak one calls, and any other function also can call:
test.h:
#ifndef TEST_H
#define TEST_H
void test(void) __attribute__((weak));
void test_default(void);
#endif
test.c:
#include "test.h"
void test_default(void) {
printf("I am the default implementation");
}
void test(void) {
test_default();
}
Anyone with access to test_default() can then call it, but whether it gets called as a result of calling test() depends on what version of test() is linked to the call -- it is weak, so a different version could be provided.
Note also that depending on the scope you want test_default() to have, it might be both possible and sensible to make it static, whereas test() must not be static as long as it is weak.
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++.
I'm writing a function that should have two versions: a debug version and non-debug version. Which one of the two functions is used should be decided by the caller.
I want something like this:
caller.c
// comment out the following line when not necessary anymore
#define MY_FUNC_DEBUG
#include "my_func.h"
// some code that calls my_func()
my_func.h
void my_func(void);
my_func.c
void my_func()
{
// lots of code
#ifdef MY_FUNC_DEBUG
// debug code
#endif
// more code
}
This obviously won't work, because my_func.c is compiled separately from caller.c, therefore it can't know what macros it defined.
How can I make this work easily? I wouldn't want to write the two versions of my_func separately, because they share most of their code.
Assuming that you are using gcc, this problem can be easily solved by defining the macro at compile time via the -D option in both files.
In your example you could compile both files using -D MY_FUNC_DEBUG when you want the debug code to be activated and nothing otherwise. There is not need for defining MY_FUNC_DEBUG in caller.c.
Make the debugging code in my_func() switchable at run-time.
my_func.h
#ifndef MY_FUNC_H_INCLUDED
#define MY_FUNC_H_INCLUDED
extern int my_func_debug(int level);
extern void my_func(void);
#endif
my_func.c
#include "my_func.h"
static int debug = 0;
int my_func_debug(int level)
{
int rv = debug;
debug = level;
return rv;
}
void my_func(void)
{
...
#ifdef MY_FUNC_DEBUG
if (debug)
...debug...
#endif
...
}
caller.c
void consumer(void)
{
int old = my_func_debug(9);
my_func();
my_func_debug(old);
}
Discussion
The outline code means that you can have one copy of the source for my_func.c, but it can be compiled with debug included, or with it excluded. The consumer code (caller.c) can request the level of debugging it wants, but whether that does anything useful depends on whether the copy of my_func.o (my_func.obj on Windows) was compiled with debug included. You get one source file; you get to choose which variant of the object file is included in the program with caller.o. And at runtime you can request debugging.
Note that my_func_debug() is unconditionally defined; it just doesn't do anything very useful if the my_func.c code is not compiled with -DMY_FUNC_DEBUG.
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.