Search code examples
cfunctioncompilationconstantsfunction-prototypes

Const in C function declaration and implementation


I have a function declared in code.h and implemented in code.c. it goes like:

void someFunc(const char*);

and

#include "code.h"
void someFunc(const char* str){ printf("%s\n", str); }

Now I found out I can remove the const in any one of the files (leaving it there in the other) and it compiles & runs with no errors. I wonder what's the meaning of this? Is one of the files the only one that matters?

It might sound like just an unimportant niche behaviour, but this fact means that a missed const can go unnoticed.


Solution

  • What happens if declaration and definition of a function don't agree on whether an argument is const or not?

    You should get a compilation error.

    What to do?

    Update your compiler.


    With gcc 4.2.1, I am receiving an error, if I remove const from either the header or the source file:

    Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c code.c
    code.c:3:6: error: conflicting types for 'someFunc'
    void someFunc(const char* str){ printf("%s\n", str); }
         ^
    ./code.h:1:6: note: previous declaration is here
    void someFunc(char*);
         ^
    1 error generated.
    

    With gcc version 4.9.2 (Debian 4.9.2-10), I am getting the same behavior.

    Same behavior with gcc's 7.1.0 version, online in Wandbox:enter image description here

    My guess is that the behavior your are experiencing is architecture/compiler's version dependent.