A
A
Andrey Akimov2014-10-21 10:49:40
C++ / C#
Andrey Akimov, 2014-10-21 10:49:40

Custom version of a function from the C standard library - is it possible?

In the source code of the C program, you need to insert your own version of the function, which is already in one of the plug-in libraries. When trying to compile, an error occurs - this function is already defined. Of course, you can change the name and there will be no problems. Is it possible to somehow "prohibit" a separate library function, without excluding the entire library, in order to be able to write and use in the program its own version with the same name?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
J
jcmvbkbc, 2014-10-21
@Ostan

Previous speakers @fornit1917 @GavriKos and @DancingOnWater suggested some weird stuff.
Just define your function and that's it. Here's an example for you:

$ cat print.c 
#include <stdio.h>
#undef printf
int printf(const char *fmt, ...)
{
        puts("my printf\n");
        return 0;
}
int main()
{
        printf("%d\n", 10);
        return 0;
}
$ gcc print.c -o print
$ ./print 
my printf

If there are compile-time errors, carefully read their text:
- perhaps the library function is defined in the header file as a macro. Use #undef to remove such a definition.
- perhaps the prototype of your implementation does not match the prototype declared in the header files. Make sure your prototype matches.
- perhaps a library function is defined in a header file. As far as I know, no standard library function does this.
This recommendation is based on the basic principles of static and dynamic linking. Ask questions if you need further clarification.

V
Vit, 2014-10-21
@fornit1917

I don't know much about C, but I can assume that you can do this with #define macros. Make a function with your own name, and then use a macro to replace the standard name with your own.

D
DancingOnWater, 2014-10-21
@DancingOnWater

Yes, of course, throw out the header of the third-party library from those files from where you need it and replace it with your own.
If this is not possible, rename your function. This is the only true way.

A
Andrey Akimov, 2014-10-21
@Ostan

The correct answer was given by jcmvbkbc - #undef should be used. I knew about it, but it still didn't work for me. As it turned out, due to the fact that I use CCTools IDE - a compiler and development environment for Android. I checked it on MVS2008 and it worked, though with warnings.

D
deleted-StrangerInRed, 2014-10-22
@deleted-StrangerInRed

and without the #undef directive it works (clion + llvm), it turns out that you are sort of implementing a function from libstd

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question