Skip to content

Instantly share code, notes, and snippets.

@framkant
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save framkant/56c8bcce57da92f125b3 to your computer and use it in GitHub Desktop.
Save framkant/56c8bcce57da92f125b3 to your computer and use it in GitHub Desktop.
Simple example of hot loading on mac
// made by @filipwanstrom
// public domain / as is
// The main.c file
#include <stdio.h>
#include <dlfcn.h>
#include <sys/stat.h>
#include <unistd.h>
typedef void (*printfunc)(void);
struct Reloadable {
char filename[256];
char symname[256];
printfunc func;
void* lib;
time_t last_modified;
};
time_t get_mod_time(const char* filename)
{
struct stat file_stat;
stat(filename, &file_stat);
return file_stat.st_mtime;
}
void bind_lib(struct Reloadable* r){
if(r->lib == NULL) {
void* f = dlopen(r->filename, RTLD_LAZY);
if(f != NULL) {
r->lib = f;
}
}else {
// unload lib first
dlclose(r->lib);
void* f = dlopen(r->filename, RTLD_LAZY);
if(f != NULL) {
r->lib = f;
}
}
void *func = dlsym(r->lib, r->symname);
if (func != NULL) {
r->func = (printfunc)(func);
}
}
void reload_if_modified(struct Reloadable * reloadable)
{
time_t n = get_mod_time(reloadable->filename);
if(n>reloadable->last_modified) {
reloadable->last_modified = n;
bind_lib(reloadable);
}
}
void printstuff(struct Reloadable * r)
{
if(r->lib !=NULL && r->func != NULL ) {
r->func();
}
}
int main (int argc, char **argv)
{
printf("Loading hotreload host\n");
struct Reloadable reloadable = {
"printfuncs.dylib",
"printstuff", NULL, NULL, 0
};
reloadable.last_modified = get_mod_time(reloadable.filename);
bind_lib(&reloadable);
while(1) {
sleep(1);
printstuff(&reloadable);
reload_if_modified(&reloadable);
}
return 1;
}
// the printfuncs.c file
#include <stdio.h>
void printstuff()
{
printf("love is everything\n");
}
// the makefile
all: printfuncs hotreload
printfuncs:
clang -dynamiclib printfuncs.c -o printfuncs.dylib
hotreload:
clang main.c -o hotreload
clean:
rm -rf hotreload printfuncs.dylib
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment