Thursday, February 3, 2022

[SOLVED] gcc error when using macro: expected ‘,’ or ‘;’

Issue

I am trying to use a macro but gcc is not happy and I am out of ideas.

gcc version and make settings:

# gcc version
gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0

# make settings
CC = gcc
WARNINGS= -Werror -Wall -Wextra -pedantic -Wcast-align -Wcast-qual -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-include-dirs -Wredundant-decls -Wshadow -Wstrict-overflow=5 -Wundef -Wno-unused -Wno-variadic-macros -Wno-parentheses -fdiagnostics-show-option
CFLAGS = $(WARNINGS) -std=c89 -I./includes
LDFLAGS = -I./includes

Code Details:

/* how the macro is definition */
#define LOG(args) (printf("LOG: %s:%d ", __FILE__, __LINE__), printf args)

/* how the macro gets called*/
LOG(("Hello, world\n"));

The error I get from gcc:

In file included from src/logging_test.c:1:
src/logging_test.c: In function ‘logging_test’:
./includes/logging.h:6:19: error: expected ‘,’ or ‘;’ before ‘(’ token
    6 | #define LOG(args) (printf("LOG: %s:%d ", __FILE__, __LINE__), printf args)
      |                   ^
src/logging_test.c:8:2: note: in expansion of macro ‘LOG’
    8 |  LOG(("Hello, world\n"));
      |  ^~~
make: *** [Makefile:81: src/logging_test.o] Error 1

After pre-processing:

# 3 "./src/logging_test.c" 2

struct TestResult logging_test()
{
 struct TestResult result = { 0, "Logger Test", "passed" }

 (printf("LOG: %s:%d ", "./src/logging_test.c", 8), printf ("Hello, world\n"));

 return result;
}

Screenshot: Screenshot


Solution

There's a semicolon missing at the end of the previous statement:

 struct TestResult result = { 0, "Logger Test", "passed" };
                                                          ^
 LOG("Hello, world\n");


Answered By - M Oehm
Answer Checked By - Cary Denson (WPSolving Admin)