Node:C++ comments,
Next:Which language,
Previous:Missing C++ headers,
Up:Compiling
Q: My C program compiles OK with Borland's C, but GCC complains
about "parse error before `/' " at a line where I have a "//"-style
comment.
A: That's because // isn't a comment neither in ANSI C nor in K&R C.
Borland and Microsoft C compilers support it as an extension. GCC also
supports this extension (beginning with version 2.7.0), but using the
-ansi
or -traditional
switches to GCC disables this
extension. In general, it's a bad practice to use this extension in a
portable program until such time as the ANSI C standard includes it. If
it's a C++ program, then rename it to have a suffix which will cause gcc
to compile it as such (see list of language-specific suffixes), or use -x
c++
switch. If it's a C program, but you want to compile it as C++
anyway, try -x c++
; it can help, but can also get you in more
trouble, because C++ has its own rules. For example, the following
program will print 10 if compiled as a C program, but 5 if compiled as
C++14:
#include <stdio.h> int main () { printf ("%d \n", 10 //* / 2 // */ 1 ); return 0; }
If you must have both -ansi
and C++-style comments, use
-lang-c-c++-comments
preprocessor switch. Gcc doesn't accept
the -lang-XXX
switches on its command line, so you will have to
use the -Wp
option, like this:
gcc -c -Wp,-lang-c-c++-comments myprog.c
Alternatively, you can add -lang-c-c++-comments
to the *cpp:
section of your lib/specs
file (but that will cause gcc
to
pass it to cpp
unconditionally).
Bottom line: until the future ANSI/ISO C standard includes this as part
of the C language, it's best to change those //
comments to
C-style ones, if you really mean to write a C program. The following
SED command will convert a C program with C++-style comments
into a valid C source, provided you don't have the string "//" in a
character string:
sed "s?//\(.*\)?/*\1 */?" file.c > newfile.c
SED can be found with the DJGPP archives on SimTel.NET, in the
v2gnu
directory.
If you want the compiler to print a warning message about usage of
//
-style comments in a C program, add the -ansi
-pedantic
options to the GCC command line. If you don't want to use
-ansi
for some reason (e.g., because it rejects some other code
that you want to keep), try using -Wp,-lang-c89
instead; this
tells the preprocessor to stick to the rules of the C89 standard.