简体   繁体   中英

Stubbing a C function that has a a parameter with the same name in C++

 int stat(const char *__restrict__ __file, struct stat *__restrict__ __buf); 

This function needs to be stubbed in order to cover more branches in an unit test made using Google Unit Test.

In file stubs.h

I have to stub this function, so I provide the following prototype:

int stat_stub(const char *__restrict__ __file, struct stat *__restrict__ __buf);

Followed by:

#define stat stat_stub
int stat_RET;

Implementation in stubs.c

int stat_stub(const char *__restrict__ __file, struct stat *__restrict__ __buf)
{
    return stat_RET;
}

The problem is that the define also replaces struct stat with struct stat_stub , and this causes a multitude of errors to appear when compiling.

I would like to know if there is a workaround to this issue, as I am currently stuck on it.

您可以使用带参数的宏。

#define stat(p1,p2) stat_stub(p1,p2)

You don't have to use macros at all, instead you can make it differ in build system.


Remove stubs.h and only use real header in production code.

In stubs.c define function with the same name:

int stat(const char *__restrict__ __file, struct stat *__restrict__ __buf)
{
    return stat_RET;
}

Now, when building production target, you link real implementation. For UT target, you build and link stubs.c .

This solution will be more versatile than macros and easier to maintain.

The root of all your problems is that you name types and functions the same thing. Simply don't do that, unless this is a C++ constructor. It doesn't look like one. The only reason this code compiles in C, is because C uses different namespaces for struct tags and function identifiers.

The solution to all your problems is not to use macros or other work-arounds, but to implement a coding standard for how you name types and functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM