This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: C++/C Linkage problems


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

>>>>> "sb" == $(C<U<.9h(B  <sb.son@partner.samsung.com> writes:

    sb> I made a library written in C++.  Instead of offering library
    sb> classes, the library offers C type library functions to the
    sb> outside.  (This library is compiled by g++)

    sb> Now, I write a program written in C and this program use
    sb> functions from the library that I mentioned above.

    sb> I wanted to compile and link this C code with gcc(c complier),
    sb> not g++(c++ compiler).  Is it possible? If so, what option
    sb> should I use?  If it's not possible, what is the solution for
    sb> this case?

    sb> Restrication : 1. Library should be written in C++ 2. The code
    sb> which use library should be written and complied by c complier
    sb> 3. I want to use gcc to link this c code.

    sb> * P.S. I don't know if "Restrication 3" is the strict one. But
    sb> 1, 2 should be kept strictly.

Yes, it is possible. Look at this:

,----[ test.cc ]
| #include <iostream>
| 
| using namespace std;
| 
| extern "C" {
|   bool prInt (int& x) {
|     cout << x << endl;
|     return cout;
|   }
| }
`----

,----[ main.c ]
| #include <stdio.h>
| 
| extern int prInt (int *x); /* [1] */
| 
| int main (int argc, char *argv[])
| {
|   printf ("%s\n", prInt (&argc) ? "good" : "failed");
| 
|   return 0;
| }
`----

Basically, you need to declare the functions you want to call from C
in your library as extern "C" to prevent the C++ name mangling scheme
being applied to them. You may just define wrapper functions that just
call a work function of your library internally:

bool cpp_prInt (int &i) { std::cout << i << std::endl; return std::cout; }
extern "C" int prInt (int i) { return cpp_prInt (i); }

* [1] of course, you need to map the C++ types to the appropriate C
  types here.

$ g++ -c -fPIC test.cc
$ g++ -shared -o libtest.so test.o
$ gcc -c main.c
$ gcc -L. main.o -ltest

$ LD_LIBRARY_PATH=. ./a.out 1 2 3 4
5
good


HTH
Claudio
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>

iD8DBQE9PQb6TpSishmp0ioRAgWsAJ0a4K4qypCq/cxO5hVxFHHkP+R1eQCdGnvy
o1kNXUK9cmz4Nmq+dzSuWs8=
=mCr1
-----END PGP SIGNATURE-----


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]