Skip to content

Instantly share code, notes, and snippets.

@mgabay

mgabay/Makefile Secret

Last active January 20, 2017 18:12
Show Gist options
  • Save mgabay/b52e5f33f0b5c2482db2b41ec16fa3b8 to your computer and use it in GitHub Desktop.
Save mgabay/b52e5f33f0b5c2482db2b41ec16fa3b8 to your computer and use it in GitHub Desktop.
An example interface with 32 and 64 bit variants
// User defines a different type
#define MYLONG int
#include "interface.h"
#include "stdio.h"
// User callback using his own type
int test(const int i, const my_long var, const int j) {
printf("i = %d\n",i);
printf("var = %lld\n",(long long) var);
printf("j = %d\n",j);
printf("%lld\n", 2LL*var-11);
return var - 7;
}
int main() {
// This is what user sees
api_func functionPtr = &test;
define_callback(functionPtr);
// Simulate callback call
call_callback();
return 0;
}
#pragma once
// MYLONG is defined differently internally and externally (before importing this file)
typedef MYLONG my_long;
// Callback definition
typedef int (*api_func)(const int, const my_long, const int); // surround by int to test alignment issues
void define_callback(api_func fptr);
void call_callback();
#define MYLONG long long
#include "interface.h"
// Callback handling
api_func callback_ptr = 0;
void define_callback(api_func fptr) {
callback_ptr = fptr;
}
void call_callback() {
(*callback_ptr)(1000, 100000, 100);
(*callback_ptr)(1000, 10000000000, 100); // will overflow when user uses int
}
CC=gcc
CFLAGS=-g -Wall -fPIC
LDFLAGS=-Wall
SRC= $(wildcard *.c)
OBJ= $(SRC:.c=.o)
all: $(OBJ) runtime runtime_static runtime_dynamic
%.o: %.c
$(CC) -c $< $(CFLAGS) -o $@
libinternal.so: internal.o
$(CC) -shared -o $@ $^ $(LDFLAGS)
libinternal.a: internal.o
ar rcs $@ $^
runtime: $(OBJ)
$(CC) $(CFLAGS) -o $@ $(OBJ) $(LDFLAGS)
runtime_static: libinternal.a example.o
$(CC) example.o -o $@ -L. -linternal $(LDFLAGS)
runtime_dynamic: libinternal.so example.o
$(CC) example.o -o $@ -L. -linternal $(LDFLAGS)
clean:
rm -f *.a *.so *.o
realclean: clean
rm -f runtime runtime_static runtime_dynamic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment