[英]How do I tell gcc to relax its restrictions on typecasting when calling a C function from C++?
我正在尝试使用Cmockery来模拟从C ++代码调用的C函数。 因为SUT是C ++,我的测试需要在C ++中。
当我像这样使用Cmockery expect_string()宏时:
expect_string(mock_function, url, "Foo");
我明白了:
my_tests.cpp: In function ‘void test_some_stuff(void**)’:
my_tests.cpp:72: error: invalid conversion from ‘void*’ to ‘const char*’
my_tests.cpp:72: error: initializing argument 5 of ‘void _expect_string(const char*, const char*, const char*, int, const char*, int)’
我在cmockery.h中看到expect_string是定义的:
#define expect_string(function, parameter, string) \
expect_string_count(function, parameter, string, 1)
#define expect_string_count(function, parameter, string, count) \
_expect_string(#function, #parameter, __FILE__, __LINE__, (void*)string, \
count)
这是_expect_string的原型(来自cmockery.h):
void _expect_string(
const char* const function, const char* const parameter,
const char* const file, const int line, const char* string,
const int count);
我认为问题在于我正在将C代码编译为C ++,因此C ++编译器反对将expect_string_count宏中的(void*)string
作为const char* string
参数传递给_expect_string()函数。
我已经在cmockery.h中使用extern "C"
包含在my_tests.cpp中,如下所示:
extern "C" {
#include <cmockery.h>
}
...为了解决名称错位问题。 (请参阅“ 如何使用已编译的C代码编译和链接C ++代码? ”)
是否有命令行选项或其他一些方法告诉g ++如何放宽对我的测试的C ++代码到cmockery.c中的C函数的类型转换的限制?
这是我目前用于构建my_tests.cpp的命令:
g++ -m32 -I ../cmockery-0.1.2 -c my_tests.cpp -o $(obj_dir)/my_tests.o
我认为这不是你的代码,但看起来更简单的方法就是通过将这个cmockery.h
为(void*)
来修复cmockery.h
(可能是使用#ifdef __cplusplus
将某些部分仅用于C ++)。
甚至可以放在你的代码中,只需重新定义expect_string_count
宏
#ifdef __cplusplus
#undef expect_string_count
#define expect_string_count(function, parameter, string, count) \
_expect_string(#function, #parameter, __FILE__, __LINE__, string, \
count)
#endif
我不认为在编译器级别有这个选项。 你可能能够解决这个问题(我假设你想避免修改CMockery源代码,因为我在你的另一个问题中已经阅读过了),通过使用CMockery的包装器头来执行类似下面的操作来使其在C和C ++:
#ifndef MY_CMOCKERY_H
#define MY_CMOCKERY_H
/*
A wrapper for cmockery.h that makes it C++ friendly while keeping things
the same for plain-old C
*/
#if __cplusplus
extern "C" {
#endif
#include "cmockery.h"
#if __cplusplus
}
#endif
#if __cplusplus
// fixup CMockery stuff that breaks in C++
#undef expect_string_count
#define expect_string_count(function, parameter, string, count) \
_expect_string(#function, #parameter, __FILE__, __LINE__, (char*)string, \
count)
#endif
#endif /* MY_CMOCKERY_H */
另一个好处是,现在你有一个地方,你可以在C ++下为CMockery提供任何其他的黑客/修复程序(希望不是太多)。
如果你想修改它可能属于它的CMockery东西 - 也许维护人员会接受你的补丁? (我不知道)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.