K&R style function definition compile using g++
-
16-06-2021 - |
Question
When compiling a c file that uses old style function definition like
int foo(a)
int a;
{
...
}
g++ will give and error: ‘a’ was not declared in this scope. gcc can parse this. Is there a way to let g++ recognize this?
This comes up as an issue to me because I'm compiling a mix of c and c++ files. A related question is what's the standard practice of building this type of mixed source? Running g++ on all files or only the cc files? The former is convenient but keeps getting me some trouble because of the inconsistencies between c and c++ specification(for example, char[4]="four";)
Solution
Is there a way to let
g++
recognize this?
This syntax is not supported in C++.
Running
g++
on all files or only the cc files?
See e.g. Compiling C++ programs from the GCC docs:
C++ source files conventionally use one of the suffixes .C', .cc, .cpp, .CPP, .c++, .cp, or .cxx; C++ header files often use .hh, .hpp, .H, or (for shared template code) .tcc; and preprocessed C++ files use the suffix .ii. GCC recognizes files with these names and compiles them as C++ programs even if you call the compiler the same way as for compiling C programs (usually with the name
gcc
).However, the use of
gcc
does not add the C++ library.g++
is a program that calls GCC and treats .c, .h and .i files as C++ source files instead of C source files unless-x
is used, and automatically specifies linking against the C++ library. This program is also useful when precompiling a C header file with a .h extension for use in C++ compilations.
So two possibilities:
- Run
gcc
on C files, andg++
on C++ files. - Run
gcc
on all files.
In both cases you will need to link with g++
(or gcc -lstdc++
).
OTHER TIPS
Oli is correct: C++ doesn't support old-style function definitions.
Compile C with a C compiler (such as gcc).
Compile C++ with a C++ compiler (such as g++).
They're two different (though closely related) languages. You can use C++'s extern "C"
feature to invoke C code from C++ and vice versa; see section 32 of the C++ FAQ Lite for more information.
If you are going to compile both C and C++, you are better off compiling always with gcc
(it will choose the language based on the file extension) than g++
(will always compile as C++). You will need to change your linker options to include C++ standard library (and -lm
if you use it) as those are automatically added by g++
but not gcc
.
Alternatively, a better option is to call the g++
for C++ and gcc
for C files. That should not be too hard to manage by configuring the build system.