Question

I'm going through Zed Shaw's tutorial on C debug macros, and am running an undeclared label problem, call the following file debug_macro.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define clean_errno() (errno == 0 ? "None" : strerror(errno))

#define log_err(M, ...) fprintf(stderr, "[ERROR] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)

#define check(A, M, ...) if(!(A)) { log_err(M, ##__VA_ARGS__); errno=0; goto error; }

int test_check(char *file_name)
{
    FILE *input = NULL;
    char *block = NULL;

    block = malloc(100);

    input = fopen(file_name, "r");
    check(input, "Failed to open %s.", file_name);

    free(block);
    fclose(input);
    return 0;

error:
    if(input) free(input);
    if(block) free(block);
    return -1;
}


int main(int argc, char *argv[])
{
    // open up a bogus file and then trigger error
    check(test_check("bogus.txt") == 0, "failed with bogus.txt");
    return 0;
}

When I compile it with either cc or gcc, I get the following error:

gcc -Wall -g -O0 -I/opt/X11/include   goto.c   -o goto
goto.c:36:5: error: use of undeclared label 'error'
    check(test_check("bogus.txt") == 0, "failed with bogus.txt");
    ^
goto.c:10:78: note: expanded from macro 'check'
#define check(A, M, ...) if(!(A)) { log_err(M, ##__VA_ARGS__); errno=0; goto error; }
                                                                             ^
1 error generated.
make: *** [goto] Error 1

shell returned 2

Press ENTER or type command to continue

When the macro is expanded, it inserts a goto error inside the test_check function, which has an error: label defined, so I don't know why I'm getting this compiler error.

Was it helpful?

Solution

You are trying to jump from main to another function test_check, but goto can only jump to a label inside the same function.

C11 §6.8.6.1 The goto statement

A goto statement causes an unconditional jump to the statement prefixed by the named label in the enclosing function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top