Skip to content

Instantly share code, notes, and snippets.

@SebastianGrans
Forked from jlintz/gist:1192247
Last active March 6, 2018 12:18
Show Gist options
  • Save SebastianGrans/8cfddc2ecbef36c44cd7e87fbd258d6d to your computer and use it in GitHub Desktop.
Save SebastianGrans/8cfddc2ecbef36c44cd7e87fbd258d6d to your computer and use it in GitHub Desktop.
Useful C debug macro.

I wanted to have a pretty way to debug my C code and found the Gist that this is a fork of. I'm kinda new with Makefiles, so I saw an oppurtunity to figure that out as well.

So how do you use this? Save all the files in this hierarchy:

├── Makefile
├── bin
├── obj
└── src
    ├── helloworld.c
    ├── mylib.c
    └── mylib.h

If you want debug messages. Compile with: > make DEBUG=y otherwise it defaults to DEBUG := n as defined in the Makefile

#include <stdlib.h> /* exit(), EXIT_SUCCESS */
#include "mylib.h"
#ifdef DEBUG
#define _DEBUG(fmt, args...) printf("%s:%s:%d: "fmt, __FILE__, __FUNCTION__, __LINE__, args)
#else
#define _DEBUG(fmt, args...)
#endif
int main() {
int a = 42;
print_hello(a);
_DEBUG("This is a debugmessage. Variable a = %d\n", a);
_DEBUG("Debugmessage without placeholders and variables.\n", NULL);
exit(EXIT_SUCCESS);
}
DEBUG := n
CFLAGS := -std=gnu99 -Werror -Wall -Wno-deprecated-declarations
ifeq ($(DEBUG),y)
CFLAGS += -DDEBUG -g
endif
.PHONY: all clean
bin/helloworld: obj/helloworld.o obj/mylib.o
$(CC) $(CFLAGS) $^ -o $@
obj/%.o: src/%.c
$(CC) $(CFLAGS) -c $< -o $@
clean:
$(RM) obj/*.o bin/*
#include "mylib.h"
void print_hello(int a) {
printf("Hello world! The answer is %d\n", a);
}
#include <stdio.h>
void print_hello(int);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment