EsmaeelE EsmaeelE - 3 years ago 218
C Question

gcc not recognize *.C source code as valid c program

I accidentally assign

.C
[note to Uppercase C ] extension to my C source code in UBUNTU 16.04 LTS and open it with Gedit program to enter my codes.

gcc compiler not recognize it as a C programming source code and produce error when it try to compile.

And UBUNTU file manager show that as a cpp file.

Code

#include <stdlib.h>

int main(){

int * c = malloc(sizeof(int));
free(c);

return 0;
}


gcc compile command, output:

$gcc test.C -o test
test.C:8:18: error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
int * c = malloc( sizeof(int) );


As we know this is a C++ specific error, and i think gcc, behave that like a C++ file as said in this
.

This is my system info

Linux ee 4.8.0-36-generic #36~16.04.1-Ubuntu SMP i686 i686 i686 GNU/Linux

gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609

gedit - Version 3.18.3


I know we simply can cast the return value of
malloc()
to
(int*)
and this will obviously works.

But we know
malloc()
return type is
void*
see linuxdie
malloc()


And it is not true to cast type of
malloc()
in C why not cast return of
malloc()


Is is true only lowercase extension is valid for C source code
.c
under UBUNTU, if true why they do this?

And if not how i can fix this and compile my
source.C
with gcc on my machine.

MCG MCG
Answer Source

GCC recognizes .C (capital letter) extension as C++ file. You need to change extension of your file to .c (small letter). Also, you rightly mentioned and referenced that C++ requires a cast in case of malloc where as in c there is an implicit conversion from any object pointer type to void *.

See below explanation about file extensions (.C and .c) from GCC documentation. Please refer below GCC link for detail explanation for various file extensions.

file.C

C++ source code which must be preprocessed. Note that in .cxx, the last two letters must both be literally x. Likewise, .C refers to a literal capital C.

file.c

C source code which must be preprocessed.

https://gcc.gnu.org/onlinedocs/gcc-3.3/gcc/Overall-Options.html

Additionally, you can give the flag -x c to force GCC to treat the file as C, not C++.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download