C: “invalid use of undefined type 'struct X' & dereferencing pointer to incomplete type” errors-Collection of common programming errors
You must move the definition of the struct
into the fraction.h
file. Unlike Java, the compiler and linker do not “magically” cause one .c
file to reference information inside another .c
file. (It could be done if you #include
one .c file in another — a bad idea.)
The directive
#include “fraction.h”
causes the text contents of the header file to be placed, as if by cut-and-paste, at the line with that directive. The compiler processes one input file at a time, reading in the #include
‘d files, and all the needed information must be present while that one .c
file is compiled.
To help with your understanding, I will point out a terrible way to accomplish what you require: simply cut-and-paste the struct definition of struct fraction
into the top of matrix.c
, immediately prior to #include "fraction.h"
— the result will compile. In Java, the compiler might complain that you have declared some duplicate types. In C, what you’ve done is define two different structs, which happen to have an identical memory layout and the same name. Only the same memory layout is needed to make them interchangable from the perspective of linking together object files.
Yes, this is a misunderstanding you picked up from Java. It’s wonderful that you are learning C!
Originally posted 2013-11-27 12:27:16.