I am trying to write some tests in Catch2 (a C++ library) for a simple C library example and I am a little confused about how to initialize a C struct.
My C header looks like this:
struct node;
And my C implementation cannot be simpler:
struct node {
int num;
struct node* next;
}
Now, the problem is with the test (in C++):
#include <catch2/catch.hpp>
extern "C" {
#include "node.h"
}
TEST_CASE("would it work?", "[foo]") {
struct node* n = (struct node*) malloc(sizeof(struct node));
}
The code will not compile because "struct node is an incomplete type".
My question, in cases like this, how do you initialize C structs like that one in C++ code? what am I doing wrong?
sizeof(struct node), but you haven't told the compiler what's instruct node. In other words, the structure definition in the C implementation needs to be visible in the C++ file. That's if you want to allocate memory for the struct in the C++ file.nodestructures. If there isn't any such function then perhaps the design or the implementation needs to be looked over? And in almost all cases you should never usemallocin C++, even for "C" structures. Generally, whenever you need to do a C-style cast then you should take that as a sign you're doing something wrong.struct node { int num; struct node* next;}in the C header "node.h" instead the C implementation.