Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the main reason not to compile c code with g++? [closed]

Tags:

c++

c

compilation

I used c in a project, and after some study, I found a better method with some c++ libraries, but I really don't want to rewrite the code (say, printf to cout).

I did some search, and I got: "They are two very different languages", "DON'T DO IT", etc, but I never found a detailed explanation.

Why? Are there some recommended articles to read?

like image 254
galagala Avatar asked Aug 19 '17 05:08

galagala


People also ask

Can you use g ++ to compile C?

gcc is used to compile C program. g++ can compile any . c or . cpp files but they will be treated as C++ files only.

What is the purpose of the C when used with the G ++ command?

Compile and link multiple files: When -c flag is used, it invokes the compiler stage which translates source code to object code. When -o flag is used it links object code to create the executable file from file_name.o to a.

What does G do in compiling?

(debug) Inserting the `g' flag tells the compiler to insert more information about the source code into the executable than it normally would. This makes use of a debugger such as gdb much easier, since it will be able to refer to variable names that occur in the source code.

What is the main reason to compile the code?

Compile is the creation of an executable program from code written in a compiled programming language. Compiling allows the computer to run and understand the program without the need of the programming software used to create it.


1 Answers

C++ is not a strict superset of C. That is, legal C code is not necessarily legal C++ code. Many of the typical differences are not syntactically valid in C++ and will fail to compile. For example:

  • Implicit void* to T* casts.
  • Using identifiers that happen to be C++ keywords.
  • Most features added to C in C99 or later.

A C++ compiler will generate errors about those, so those aren't too hard to find and fix if you have some patience.

Some differences could be valid in both languages but behave differently, however. Such cases are harder to detect. Some examples are shown at:

  • Can code that is valid in both C and C++ produce different behavior when compiled in each language? (as pointed out by 4386427's comment)
  • Write a program that will print “C” if compiled as an (ANSI) C program, and “C++” if compiled as a C++ program
like image 105
jamesdlin Avatar answered Sep 21 '22 18:09

jamesdlin