Compiling C Programs with GCC: Addressing Linker Errors
The GCC compiler is capable of compiling C programs. However, encountering linker errors during compilation, as seen in the provided example, may lead to the incorrect assumption that GCC cannot compile C .
Understanding the Linker Errors
The linker errors reported are not related to GCC's ability to compile C . They indicate missing references to functions and libraries required for C programs. Specifically, the errors refer to symbols not found in the standard C library, which is the default library linked by GCC.
Fixing the Errors by Linking to the C Standard Library
To resolve the linker errors, it is necessary to link the C program against the C standard library. This can be done by modifying the compilation command as follows:
gcc info.C -lstdc++
The -lstdc flag instructs GCC to link the program with the standard C library, which contains the definitions for the missing symbols.
Alternative: Using g
Alternatively, it is recommended to use the dedicated C compiler, g , which simplifies the compilation process. g understands the C language semantics and automatically links to the C standard library by default.
Difference Between gcc and g
As explained by Rup in the answer provided, gcc selects the backend compiler based on file extension, but it links to only the standard C library by default. On the other hand, g also selects the backend based on extension, but it compiles both C and C source as C and links with the C standard library, regardless of the file extension.
The above is the detailed content of Why Do I Get Linker Errors When Compiling C with GCC, and How Can I Fix Them?. For more information, please follow other related articles on the PHP Chinese website!