Re: default argument and shared library
On Aug 3, 8:36 am, S S <sarvesh.si...@gmail.com> wrote:
Here is the situation,
I have one line "a.h" as below
extern "C" void afun(int a)
I have "a.cc" as below
#include<iostream>
using namespace std;
extern "C" void afun(int a)
{
cout << "A= " << a;
}
I have "main.cc" as below
#include<iostream>
#include "a.h"
using namespace std;
int main()
{
afun(10);
return 0;
}
Now I compile the a.cc file and create a shared library a.so
g++ -shared -fPIC a.cc -o a.so
Now I compile main.cc using a.h and a.so and create executable a.out
g++ -g a.h main.cc a.so
When I run executable 'a.out', I get output as below
A= 10
which is of course correct.
Now I modify a.h and a.cc with one extra argument as below,
a.h
===
extern "C" void afun(int a, int b = 1);
a.cc
===
#include<iostream>
using namespace std;
extern "C" void afun(int a, int b)
{
cout << "A= " << a << "B= " <<b;
}
Now I again update my a.so with below command
g++ -shared -fPIC a.cc -o a.so
But I do not want to update my a.out, I want new shared file
to be used with old executable 'a.out' and that is the sole
purpose of adding default argument (otherwise non default
argument could also be the choice).
You can't. You've changed the interface. If the function
wasn't ``extern "C"'', you could use overloading, but as it is,
the only solution is to introduce a new function, with a
different name, which takes two arguments.
But when I run a.out, I get
A= 10 B= -18776767
which is ofcourse garbage value.
Why default argument is not reflected in shared file and the
executable?
Because the default argument is only used at the call site. A
function
void afun( int a, int b = 1 ) ;
, is a function which takes two arguments, both of which have
type int. The ``= 1'' only comes into play at the call site,
telling the compiler what to pass if you don't provide a value.
If your function hadn't been ``extern "C"'', you'd probably have
gotten an error from the dynamic link, saying it couldn't find
the function.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34