开发者

Changing value of preprocessor symbol for testing

开发者 https://www.devze.com 2023-01-16 07:24 出处:网络
I am writing a dynamically growing string buffer. I have the following in a .c file. #ifndef STRBUF_GROWTH_SIZE

I am writing a dynamically growing string buffer. I have the following in a .c file.

#ifndef STRBUF_GROWTH_SIZE
#define STRBUF_GROWTH_SIZE 4096
#endif

My code uses this constant to do the reallocation of the buffer. Now in the tests, I need to set this value to a开发者_如何学运维 small one so that I can check the reallocation. I tried defining this in the tests.cpp (All tests are in C++ using UnitTest++).

#define STRBUF_GROWTH_SIZE 10
TEST(StringBuffer)
{
    struct strbuf *string = strbuf_init();

    strbuf_add(string, "first");
    CHECK_EQUAL("first", string->buffer);
    CHECK_EQUAL(5, string->length);
    CHECK_EQUAL(10, string->allocated);   /* this fails */

    strbuf_add(string, " second");
    CHECK_EQUAL("first second", string->buffer);
    CHECK_EQUAL(12, string->length);
    CHECK_EQUAL(20, string->allocated); /* this fails */

    strbuf_destroy(string);
}

I am wondering why the value didn't change to 10? How can I workaround this problem?

Any thoughts?


The #define in your test isn't seen by your code in the other .c file. However, you can inject the macro in your build. With gcc its the -D argument. With msvc's cl its the /D argument.


Preprocessing is done on a source-file-by-source-file basis (well, not quite, but it's close enough). A #define in one source file won't affect anything in another source file.

You'll either need to #define this in a header, which you can swap out with another header during testing, or you'll need to parameterise your library (e.g. strbuf_init(int growth_size).

Alternatively, why don't you just test with strings that are of length-4096? Then you'll be testing your actual production code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号