Skip to content

Instantly share code, notes, and snippets.

@chris-marsh
Created January 5, 2017 21:14
Show Gist options
  • Save chris-marsh/1f4068bbae10668517e6aface3c4bc35 to your computer and use it in GitHub Desktop.
Save chris-marsh/1f4068bbae10668517e6aface3c4bc35 to your computer and use it in GitHub Desktop.
Design pattern: First Class Abstract Data Type
#include <gtk/gtk.h>
#include <string.h>
#include <stdlib.h>
typedef struct Window* WindowPtr;
struct Window {
char *title;
GtkWidget *win;
};
static void print_msg (GtkButton *button, WindowPtr window) {
puts(window->title);
}
WindowPtr create_window(const char *title) {
WindowPtr window = malloc(sizeof *window);
if (window) {
window->title = malloc(strlen(title)+1);
strcpy(window->title, title);
GtkWidget *button;
window->win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_window_set_type_hint(GTK_WINDOW(window->win), GDK_WINDOW_TYPE_HINT_DIALOG);
gtk_window_set_title(GTK_WINDOW(window->win), title);
gtk_window_set_default_size(GTK_WINDOW(window->win), 200, 200);
g_signal_connect (GTK_WIDGET (window->win), "destroy", G_CALLBACK (gtk_main_quit), NULL);
button = gtk_button_new_with_label("Click me");
gtk_container_add(GTK_CONTAINER(window->win), button);
g_signal_connect(button, "clicked", G_CALLBACK(print_msg), window);
gtk_widget_show_all(window->win);
}
return window;
}
void destroy_window(WindowPtr window) {
if (gtk_main_level() !=0 && window->win != NULL)
gtk_widget_destroy(window->win);
free(window);
}
#include <gtk/gtk.h>
typedef struct Window* WindowPtr;
WindowPtr create_window(const char *title);
void destroy_window(WindowPtr window);
int main(int argc, char *argv[]) {
gtk_init(&argc, &argv);
WindowPtr win1 = create_window("The Title");
WindowPtr win2= create_window("Another windy!");
gtk_main();
destroy_window(win1);
destroy_window(win2);
CC=gcc
CFLAGS=-std=c99 -g -Wall
GTKFLAGS=`pkg-config --cflags --libs gtk+-3.0`
GTKLIBS=`pkg-config --cflags --libs gtk+-3.0`
gui: main.c gui.c
$(CC) main.c gui.c -o gui $(EXECUTABLE) $(CFLAGS) $(GTKFLAGS)
.PHONY: clean
clean:
rm -f gui
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment