2011-01-06 3 views
3

Cmockeryを使って、C++コードから呼び出されたC関数をモックしようとしています。 SUTはC++になっているので、私のテストはC++で行う必要があります。C++からC関数を呼び出すときに型キャストの制限を緩和するにはどうすればgccに指示しますか?

私はこのような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)’ 

私はexpect_stringが定義されているcmockery.hに参照してください。

#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++コンパイラはconst char* stringパラメータ_expect_stringに()関数として渡されるexpect_string_countマクロに(void*)stringに反対していることであると信じています。名前マングリングの問題を回避するために...

extern "C" { 
#include <cmockery.h> 
} 

:私はcmockery.h周りextern "C"をすでに使用してきました

は次のようにmy_tests.cppに含めます。 (How do I compile and link C++ code with compiled C code?

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 

答えて

3

は、私はそれはあなたのコードではありませんundersatand、もっと簡単な方法は、このキャストを除去することにより、cmockery.hを修正するために、おそらくあるように見えます(void*)(一部のセクションはC++のためだけに有効ですが、#ifdef __cplusplusを使用している可能性があります)。でも私は、コンパイラレベルで、このためのオプションがないと思う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 
2

を再定義し、あなたのコードに入れることができ

。あなたはこれを回避することができるかもしれません(別の質問で読んだコメントのために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のものを修正しようとしているのでしょうか? (私は知らないよ)。

関連する問題