Search code examples
c++compilationg++

G++ failed to compile __attribute__ keyword


I tried compiling attribute with g++, but failed, gcc will compile successfully. g++ test.c -o test

Here is the function:

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

struct student{
    int num;
};

static __inline int student_information (struct student *) __attribute__((__unused__));
static __inline int student_information(stu) struct student *stu;
{
    return 0;
}

int main(void)
{
    struct student *stu = (struct student *)malloc(sizeof(struct student));
    student_information(stu);

    return 0;
}

Here is the failture message:

test.c:9:44: error: ‘student_information’ declared as an ‘inline’ variable
 static __inline int student_information(stu) struct student *stu;
                                            ^
test.c:9:44: error: ‘int student_information’ redeclared as different kind of symbol
test.c:8:21: error: previous declaration of ‘int student_information(student*)’
 static __inline int student_information (struct student *) __attribute__((__unused__));
                     ^
test.c:9:41: error: ‘stu’ was not declared in this scope
 static __inline int student_information(stu) struct student *stu;
                                         ^
test.c:10:1: error: expected unqualified-id before ‘{’ token
 {
 ^
test.c:8:21: warning: inline function ‘int student_information(student*)’ used but never defined [enabled by default]
 static __inline int student_information (struct student *) __attribute__((__unused__));

I don't know why this is wrong, but how do I compile attribute with g++


Solution

  • It's because g++ is a C++ compiler and you're giving it invalid C++: it has to reject this code, so it just tells you why and quits. Also, the __attribute__ keyword is a compiler-specific extension, which in this case could be replaced by [[maybe_unused]]. In fact nothing in standard C++ starts with any underscores: such names are reserved for use as custom extensions or implementation details by compiler and standard library implementations.