Home > Blockchain >  Handling OS function name mismatch with macros
Handling OS function name mismatch with macros

Time:10-27

My current code is:

int my_func(int a) 
{
    #ifdef _WIN32
    return _func(a);
    #else
    return func(a);
    #endif
}

But I think it would be better if it was something like:

#ifdef _WIN32
#define common_func(a) _func(a);
#else
#define common_func(a) func(a);
#endif

int my_func(int a) 
{
    return common_func(a);
}

Now, I have never done this and I don't know what I am doing. The K&R cat() example is confusing. I basically just want to get the #ifdefs out of the function because it would get too messy because I have to run the function several times.

func() and _func() are the same function, just Windows thought it would be a great idea to prepend it with an underscore. So it's not even a macro function but more like a function alias maybe. Or a wrapper?

Does this impact performance? Does the generated code differ from version 1? Is there some trick, since the difference is just the underscore?

I want to do it correctly and properly. Please help.

CodePudding user response:

Windows thought it would be a great idea to prepend it with an underscore. So it's not even a macro function but more like a function alias maybe. Or a wrapper?

Most likely it's simply a differently-named function that has the same specifications. Probably not a wrapper or alias. Functions such as POSIX open(), read(), and write() are not defined by the C language specification, unlike corresponding fopen(), fread(), and fwrite(). Generally speaking, C implementations must provide the latter group, by they have no obligation to provide the former group.

Does this impact performance?

Conditional compilation directives such as #ifdef are evaluated at compile time. They themselves have no runtime impact at all, and they are pretty cheap at compile time.

Does the generated code differ from version 1?

No. The two versions of your code are 100% equivalent.

Is there some trick, since the difference is just the underscore?

If there are several functions you want to use where the Windows versions differ in name from (I suppose) the POSIX version by a leading underscore, then you might think it worth your while to define a common macro that you can reuse for all of them, instead of rolling a separate thing for each individual function. Maybe something like this:

#ifdef _WIN32
#define POSIX_MANGLE(f) _ ## f
#else
#define POSIX_MANGLE(f) f
#endif

You would use that something like so:

void do_something(int a) {
    POSIX_MANGLE(func1)(a);
    POSIX_MANGLE(func2)(a);
}

On Windows (technically, wherever _WIN32 is defined), that is then equivalent to ...

void do_something(int a) {
    _func1(a);
    _func2(a);
}

Anywhere else, it is equivalent to ...

void do_something(int a) {
    func1(a);
    func2(a);
}
  •  Tags:  
  • c
  • Related