[英]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.