Skip to content

Instantly share code, notes, and snippets.

@twopoint718
Created March 16, 2022 22:07
Show Gist options
  • Save twopoint718/91bc51f1bb9bb81d8388b82be01d2782 to your computer and use it in GitHub Desktop.
Save twopoint718/91bc51f1bb9bb81d8388b82be01d2782 to your computer and use it in GitHub Desktop.
Public/private struct members in C
#include <stdio.h>
/* #include "private.h" */
#include "public.h"
#include "s.h"
int main() {
struct s foo;
init_s(&foo);
printf("foo.public.a %d\n", foo.public.a);
printf("foo.public.b %d\n", foo.public.b);
// won't compile w/o private.h
/* printf("foo.private.c %d\n", foo.pointer_to_private->c); */
return 0;
}
struct secretStuff {
int c;
};
struct secretStuff; // prototype tells linker this is later defined
struct s {
struct {
int a;
int b;
} public;
struct secretStuff *pointer_to_private;
};
#include "private.h"
#include "public.h"
// A secret-aware function to initialize the struct
void init_s(struct s* new) {
new->public.a = 25;
new->public.b = 50;
new->pointer_to_private->c = 75;
}
void init_s(struct s* new);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment