Compiling C program in C++ compiler - c++

I wrote a program in C and I want to use C++ library in this code, I though that I will be able to compile the C in g++ since C++ built in top of C. However, I couldn't do that and the main error was because in one part of the code I wrote a function to read data from input file, before the main function. That worked well in C compiler but not in Cpp compiler.
Below is some of the error messages I got, so I'd like to get general comments and points to take into consideration when use c and cpp interchangeably
error : ‘get_inputs’ was not declared in this scope
error: use of parameter outside function body before ‘]’ token

Following program compiles in C with a warning such as: 'bar' undefined; assuming extern returning int
void foo()
{
bar(5);
}
int bar(int x)
{
return x*2;
}
If you want this to compile in C++ you must declare bar before you use it:
int bar(int x); // forward declaration
void foo()
{
bar(5);
}
int bar(int x)
{
return x*2;
}
Even in C it's good practice to use forward declarations and to enable all compiler warnings otherwise the error in following program will slip through:
void foo()
{
bar(); // calling bar without argument....
}
int bar(int x)
{
return x*2; // ... will result in an undefined value for x here
}

Related

Function pointer type cannot be used for a function prototype

I'd like to know why the following snippet does not work:
typedef void (*MYFUNC_PTR)(int a);
MYFUNC_PTR myFunc;
void myFunc(int a)
{
}
I'm using Microsoft Visual Studio 2017. The source file is ".c", but I tried the same with ".cpp". The error I'm getting is
Error C2365 'myFunc': redefinition; previous definition was 'data variable'
NOTE: I assumed this code would work because Microsoft mentions a similar snippet (which does not work either, as I tested that one, too), for example here.
EDIT: I thought maybe this only works in one of the newer C++ standards, but that's not the case either, as I tried C++17.
A function pointer isn't the same thing as a function declaration, so this simply doesn't work. You can do this, however:
typedef void(*MYFUNC_PTR)(int a);
MYFUNC_PTR myFunc;
void someFunc(int a)
{
}
int main() {
myFunc = someFunc;
return 0;
}
The problem is that the type of myFunc is a function pointer, not a function. After that you're defining myFunc as a function (, of course), they don't match.
You can change the typedef for MYFUNC_PTR to function, then
typedef void(MYFUNC_PTR)(int a);
MYFUNC_PTR myFunc;
void myFunc(int a)
{
}
LIVE

C++ name mangling in C

C language does not use name mangling like C++. This can lead to subtle bugs, when function prototype is declared differently in different files. Simple example:
/* file1.c */
int test(int x, int y)
{
return y;
}
/* file2.c */
#include <stdio.h>
extern int test(int x);
int main()
{
int n = test(2);
printf("n = %d\n", n);
return 0;
}
When compiling such code using C compiler (in my case gcc) no errors are reported. After switching to C++ compiler, linking will fail with error "undefined reference to 'test(int)'". Unfortunately in practice this is not so easy - there are cases when code is accepted by C compiler (with possible warning messages), but compilation fails when using C++ compiler.
This is of course bad coding practice - all function prototypes should be added to .h file, which is then included in files where function is implemented or used. Unfortunately in my app there are many cases like this, and fixing all of them is not possible in short term. Switching to g++ is also not at option, I got compilation error quite fast.
One of possible solutions would be to use C++ name mangling when compiling C code. Unfortunately gcc does not allow to do this - I did not found command line option to do this. Do you know if it is possible to do this (maybe use other compiler?). I also wonder if some static analysis tools are able to catch this.
Using splint catches these kinds of errors.
foo.c:
int test(int x);
int main() {
test(0);
}
bar.c:
int test(int x, int y) {
return y;
}
Running splint:
$ splint -weak foo.c bar.c
Splint 3.1.2 --- 20 Feb 2009
bar.c:1:5: Function test redeclared with 2 args, previously declared with 1
Types are incompatible. (Use -type to inhibit warning)
foo.c:4:5: Previous declaration of test
Finished checking --- 1 code warning
~/dev/temp$ cat > a.c
int f(int x, int y) { return x + y; }
~/dev/temp$ cat > b.c
extern int f(int x); int g(int x) { return f(x + x); }
~/dev/temp$ splint *.c
Splint 3.1.2 --- 03 May 2009
b.c:1:12: Function f redeclared with 1 arg, previously declared with 2
Types are incompatible. (Use -type to inhibit warning)
a.c:1:5: Previous declaration of f
Finished checking --- 1 code warning
~/dev/temp$

Use case of C++11 function declaration at block scope?

It would seem I can declare a function at block scope:
int main()
{
void f(); // OK
}
However I can't define it:
int main()
{
void f() {}; // ERROR
}
My question is, of what use is a function declaration at block scope? What is a use case?
It's sometimes a shortcut to declaring and calling an externally-linked function which itself isn't publically defined in a header. For example, imagine you were linking against a C library which you knew provided a LibDebugOn(int) call but hadn't defined it in a header. It can be a shortcut to declare and call it in one place:
void myFunc() {
// call "Lib" but turn on debugging via hidden API
extern "C" void LibDebugOn(int); // declare hidden C-linked function
LibDebugOn(1); // call it
// do something with the library here...
LibDebugOn(0); // turn off lib debugging now
}
In fairness this is usually only worthwhile for a one-off quick hack, and not something to be encouraged.
You can define it. http://ideone.com/kJHGoF
#include <cstdio>
int main()
{
void f(); // Forward declare function named "f" returning void in the
// global namespace.
f();
}
/*
void g()
{
f(); // ERROR!
}
*/
void f()
{
std::puts("hello!");
}
I'm not sure why someone would actually want to use this. It is in the language this way for backwards compatibility with C; but I've got no idea what someone would do with this in C.

From where does the compiler start reading

This is a small program :
#include <iostream>
using namespace std;
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
The error that i get here is :error C3861: 'f': identifier not found
If i place the function f above main I will get the desired output.
Why it is so ?
I was told that program execution begins at main. According to this the code should run in the first case also.
How does the compiler start reading the program?
The beginning of the compilation and the beginning of the execution of the program are two different things.
The execution starts from the main.
The compilation begins from the beginning of the file; the compiler don't "jump around" the file to find the needed pieces, but it reads the input in a linear fashion (I suspect that this related, among the other things, to the fact that the C++ grammar is really complicated).
When the compiler is at some point in parsing the file, it only knows what has been declared/defined up to that point1.
Because of this, function prototypes (and non-defining declarations in general) have been invented: the prototypes of all the functions defined in the file are put at the beginning of the file, typically after the #include directives or in a separated include file. The prototypes tell to the compiler that such functions will be defined later, and what is the function signature (i.e. name, parameters, return value).
The prototype is made as a normal function, but without the body, which is replaced by a semicolon2. For example, in your code you would write
void f();
before the main.
IIRC there are some relaxations to this rule that allow the compiler to "wait" for some declarations to make some template magic work, but this is not relevant here.
In a prototype is also common not to write the names of the parameters, leaving just their type (this can be done also in function definitions, but it doesn't make much sense there unless you have a formal parameter you don't use). Still, I prefer to leave the parameter names there as a form of documentation.
I was told that program execution begins at main.
And that's exactly the point.
The compiler starts from main, and then sees a call to f(), which it has not encountered so far (as it is defined afterwards), so it does not know what to do with it.
If you want to define f after main you can place a function prototype before, such as
#include <iostream>
using namespace std;
void f(); // <--- This tells the compiler that a function name f will be defined
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
To be able to call a function it must have been declared at some earlier point in the code. This is just a rule of the language designed to help compilers.
You can declare the function earlier with e.g.
void f();
...and then define it after main as you have done.
The compiler starts at the top and reads down to the bottom.
you'll need to have something like:
#include <iostream>
using namespace std;
void f();
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
No, the compiler needs to see at least a declaration of f() before it is used. A c(++) code file is a simple text file and must be read from begin to end by the compiler.
During the compilation process, when the compiler is evaluating main() it needs to know what f() is in advance to be able to generate the correct assembly code to call this function. That's why you need to put it before main() in this case.
As an alternative you can declare the prototype of f() before main() so the compiler knows it's a local function declared somewhere else on your file:
void f(); // prototype
int main()
{
// .. code ..
}
void f() // implementation of f()
{
// .. code ..
}

Borland c++ exception

i am using the Borland c++ 3.1 compiler. I want to work with exceptions, i've written the following code:
void main (void) {
int a = 0;
int b = 1;
int c;
try {
throw 1;
}
catch(int a) {
b = a;
}
}
The compiler returns a syntax error. what's wrong?
Most compilers will issue an error stating that your main function must return an int.
The main function must return int in a C++ program. It's unsafe to return void from a main function and many modern compilers won't compile. Aside from that everything looks compilable