Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Naming Conventions of C: A struct and a function

Tags:

c

linux

While exploring the facilities for handling system signal requests in the sigaction.h header, I noticed that a structure and a function returning an int were named sigaction.

Even though it seems semantically correct, since the compiler should be able to deduce between the two definitions, why are the duplicate definitions of sigaction valid C syntax?

like image 285
edition Avatar asked Dec 20 '22 00:12

edition


2 Answers

In C, struct tags live in a separate namespace from the other names. The struct is called struct sigaction, while the function is simply sigaction.

like image 149
Quentin Avatar answered Jan 05 '23 11:01

Quentin


The compiler is able to separate structure tags (also unions and enumerations) because they're following the keywords struct/union/enum, respectively (C11 §6.2.3p1).

Then, declarations are required to be unique within "the same name space", according to §6.7p3.

Since structure tags and function identifiers (which are ordinary identifiers) aren't in the same name space, the "clash" is OK.

When it comes to usage, you can't do:

typedef struct _test {
    int a;
} test;

void test(void) {

}

The compiler will inform you:

test.c:5:6: error: 'test' redeclared as different kind of symbol
 void test(void) {
      ^
test.c:3:3: note: previous declaration of 'test' was here
 } test;
like image 34
Michael Foukarakis Avatar answered Jan 05 '23 10:01

Michael Foukarakis