When compiling C or C++ code with GCC, you may encounter the error “dereferencing pointer to incomplete type”. This means the compiler knows that a type exists, but it does not yet know the type’s complete structure when your code tries to access one of its members.
What is an incomplete type?
An incomplete type is a type that has been declared but not fully defined. A common example is a forward declaration:
struct Device;
struct Device *device;
At this point, the compiler knows that struct Device exists and can work with a pointer to it. However, it does not know the fields inside the structure.
Why does the error occur?
A pointer to an incomplete type can be declared, passed to functions, or compared with another pointer. However, the compiler cannot dereference it to access a member because the structure layout is unknown.
struct Device;
void display(struct Device *device) {
/* Error: the structure has not been fully defined */
printf("%d", device->status);
}
How to fix it
Define the complete structure before dereferencing the pointer. The definition must be visible in the source file where you access its members:
struct Device {
int status;
};
void display(struct Device *device) {
printf("%d", device->status);
}
Header files and include order
In larger C and C++ projects, the structure definition is usually placed in a header file. Include that header before using the structure’s members:
/* device.h */
#ifndef DEVICE_H
#define DEVICE_H
struct Device {
int status;
};
#endif
#include "device.h"
void display(struct Device *device) {
printf("%d", device->status);
}
Use forward declarations in headers when you only need to store or pass pointers. Include the full definition in the implementation file when you need to access fields or methods.
Common C++ example
The same issue can happen with classes. A forward declaration is enough for a pointer or reference, but not for member access:
class Engine;
class Car {
public:
Engine *engine;
void start();
};
The implementation of Car::start() must include the header that contains the complete definition of Engine if it accesses the object’s members.
Quick checklist
- Find the pointer being dereferenced in the compiler error.
- Check whether its type is only forward-declared.
- Include the header containing the complete structure or class definition.
- Check for circular includes and use include guards or
#pragma once. - Rebuild the project after correcting the include or definition order.
Conclusion
The error is caused by trying to access members of a type whose full definition is not visible at that point in the code. Keep forward declarations for interfaces that only use pointers or references, and include the complete definition wherever member access is required.
Watch the video
Watch the accompanying explanation:
Tags: syntax, GCC, compiler errors, compiler design, C++, C programming, programming for beginners.