Home > OS >  malloc with C struct in C
malloc with C struct in C

Time:10-23

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?

CodePudding user response:

Basically everything has already been said in the comments.

You are just forward declaring the struct in the header. While it is best practice to use forward declarations to reduce include dependencies in headers that just need to know what something is (e.g. a struct) but not what it contains, it usually doesn't make much sense to forward declare the struct in the header that is actually supposed to define the struct itself.

Using a struct (including malloc) beyond just needing to know that it is a pointer or a reference requires knowledge of the definition of that struct. Note that your C file only sees the contents of the included header; it doesn't see the contents of the C file. Therefore, the forward declaration in the header should replaced by the struct definition from the C file, making the C file obsolete in case it was really only intended to define the struct.

  • Related