delorie.com is funded by banner ads.
  www.delorie.com/djgpp/v2faq/faq053.html   search  

| Previous | Next | Up | Top |

8.3 GCC barfs on C++-style comments in C programs

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++(Note: While admittedly perverse, this little monstrosity was written with the sole purpose of demonstrating that C and C++ have quite different semantics under certain circumstances.):
         #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 make it permanent).

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.


  webmaster   donations   bookstore     delorie software   privacy  
  Copyright ⌐ 1998   by Eli Zaretskii     Updated Sep 1998  

Powered by Apache!

You can help support this site by visiting the advertisers that sponsor it! (only once each, though)