Warm tip: This article is reproduced from serverfault.com, please click

c-使用宏时的gcc错误:预期为','或';'

(c - gcc error when using macro: expected ‘,’ or ‘;’)

发布于 2020-11-28 12:47:46

我正在尝试使用宏,但gcc并不满意,我没有主意。

gcc版本并进行设置:

# 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

代码详细信息:

/* 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"));

我从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

经过预处理:

# 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;
}

截屏: 截屏

Questioner
Infomorph
Viewed
0
M Oehm 2020-11-28 21:01:02

前一条语句的末尾缺少分号:

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