What are opaque types in C ? How do you use them ?
Abdul Hameed Oluwashegu Tade
System Software Engineer @ Turntabl | Computer Engineering Degree
Sometimes when working with C, you might want to perform some data abstraction. There is an easy technique to do this in C using opaque types.
Opaque.c contains the definition of the struct. In opaque.h, we declare the struct, but this time we do not define its fields. We use the extern keyword to tell the compiler/linker that the definition of the struct is in another file. Let's write a test program to use this struct. Open an editor, create the file test.c, and copy the following into it.
#include <stdio.h>
#include "opaque.h"
int main()
{
? ? char name[256] = "Jerome Boateng";
? ? char Country[256] = "Ghana";
? ? unsigned long long age = 30;
? ? Opaque* op = CreateHuman(name,Country,age);
? ? PrintHuman(op);
OpaqueFree(op);
}
Compiling and running on Ubuntu-18.04 LTS WSL with gcc 9.3.0 by typing the commands below,
1| gcc -o test test.c opaque.c
2| ./test
we get the following output:
领英推荐
1| -------------------------------------------------
2| Name:? ? ? ?Jerome Boateng
3| Country:? ? Ghana
4| Age:? ? ? ? 30
5| -------------------------------------------------
The CreateHuman function takes a structure of type Opaque, populates the fields of the structure with the arguments provided, namely the name and country of origin as character strings and then an age of type unsigned long long. It then passes the Opaque struct to PrintHuman which then formats and prints the corresponding fields to standard output (screen). OpaqueFree is then called, which frees the allocated block .
So everything works fine as you can see. What we have essentially done here is data abstraction. We declared the struct with its fields in the C source file, but in the header file, we qualified the declaration of the struct name with the extern keyword which tells the linker to look elsewhere, in another file, for the actual definition of the fields of the Opaque structure. That way, any source file using the structure would only be able to declare it but not get access to the fields of the structure.
This technique is used all over the C runtime library to hide its internal data structures from user mode programs that use it.
Thanks for reading. Leave a comment, like and suggest corrections in case you find mistakes.
Acknowledgement
Thanks to Stephan Luik for the correction on the memory leak issue.
Software Engineer | Technical Writer
3 年Came from the memory allocation post. Your ability to lucidly transfer technical concepts in writing is amazing! Kudos I think it's time I digged into C/C++??
If you are trying to mimic C++ classes, don't forget to implement the destructor method. Otherwise, the only opaque things you are implementing are memory leaks.??