danwritecode / clings

rustlings for C....clings
MIT License
42 stars 7 forks source link

Optimizing Debugging Checks: From Runtime Boolean to Compile-Time Macros #149

Closed 7etsuo closed 4 months ago

7etsuo commented 4 months ago
const bool DEBUG_MODE = false;
...
            if (DEBUG_MODE == true) {
                display_debug(&exercise);
                continue;
            }

rather than using a bool here it might be better to just use a macro for example

    #ifdef DEBUG
                display_debug(&exercise);
                continue;
    #endif // DEBUG

You would then compile with gcc -DDEBUG main.c -o main

danwritecode commented 4 months ago

I like this, this makes things cleaner.

If using Make, how does it get compiled in DEBUG_MODE? Is it possible to pass the debug argument at runtime instead and achieve the same?

7etsuo commented 4 months ago

You can do it a couple of ways.

  1. Using environment variables, like you said.

    bool debug_mode() {
    return getenv("DEBUG_MODE") != NULL;
    }

    Then you could run it with DEBUG_MODE=1 ./main

  2. Parse command line arguments to main(). You would have to change the prototype to int main(int argc, char **argv); then you would do something like ./clings --dbug

  3. Best option. Add DEBUG_MODE to your make file so you can just make debug when you want to build it with debugging on.

    
    CC = gcc
    CFLAGS = -Wall -Wextra -Werror

SRCS = main.c files.c utils.c runna.c exercise.c OBJS = $(SRCS:.c=.o)

TARGET = clings

all: $(TARGET)

debug: CFLAGS += -DDEBUG # added this line debug: $(all) # and this line

$(TARGET): $(OBJS) $(CC) $(CFLAGS) -o $(TARGET) $(OBJS)

%.o: %.c $(CC) $(CFLAGS) -c $< -o $@

clean: rm -f $(OBJS) $(TARGET)

.PHONY: all clean


Then when you run it debugging is on when you add the #if macros.