Writing cross-platform tests for C code

I'm sick of Visual Studio and its viscerally vulgar shitty shenanigans.

Feb 2, 2025

Rolling back on my previous post regarding C tests in Visual Studio, I have since switched back to using unity for writing tests for C code since it' easier to use across different platforms.

Folder structure:

some_folder/
    foo/
        foo.c
        foo.h
    bar/
        bar.c
        bar.h
test/
    tests/
        test_foo.c
        test_bar.c
    unity/
        unity.c
        unity.h
        unity_internals.h

Personally I like to write my Windows code without the CRT, so I compile everything except my tests without it.

file(GLOB_RECURSE SRC_FILES "**/*.c")
list(FILTER SRC_FILES EXCLUDE REGEX "/main\\.c$")
list(FILTER SRC_FILES EXCLUDE REGEX "/test/.*\.c$")
list(FILTER SRC_FILES EXCLUDE REGEX "build")

file(GLOB UNITY_SRC "test/unity/*.c")
file(GLOB UNITY_HEADERS "test/unity/*.h")
file(GLOB_RECURSE TEST_SOURCES "test/tests/*.c")

foreach(test_source IN LISTS TEST_SOURCES)
    get_filename_component(test_name ${test_source} NAME_WE)
    add_executable(${test_name} ${test_source} ${UNITY_SRC} ${UNITY_HEADERS} ${SRC_FILES} ${HEADERS})

    if(MSVC)
        target_compile_options(${test_name} PRIVATE /D_CRT_SECURE_NO_WARNINGS /MT /EHsc)
        set_target_properties(${test_name} PROPERTIES
            COMPILE_OPTIONS ""
            LINK_OPTIONS ""
        )
    else()
        target_compile_options(${test_name} PRIVATE -DCRT)
    endif()

    enable_testing()
    add_test(NAME ${test_name} COMMAND ${test_name})
endforeach()

And here is an example of a test file:

#include "unity.h"
#include "foo.h"

void setUp(void)
{
}

void tearDown(void)
{
}

void test_foo(void)
{
    TEST_ASSERT_EQUAL(0, foo());
}

void test_foo2(void)
{
    TEST_ASSERT_EQUAL(0, foo());
}

int main (void)
{
    UNITY_BEGIN();
    RUN_TEST(test_foo);
    RUN_TEST(test_foo2);
    return UNITY_END();
}

Now without worries about the CRT or cross-platform compatability issues, you can write tests for your C code using unity (provided that you didn't write any code that depends on the CRT and have added in macros for portability, look for further posts regarding this).

Drake saying no to visual studio