943,724 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 1587
  • C RSS
Jan 5th, 2009
0

Calling C++ function from C code

Expand Post »
Hello,
I'm quite new here, but there's a problem that needs solution. I think the title says exactly what I want to do. I need to use C for a reason I don't think is this important to mention. I tried searching Google, and found the same solution on most of the results.
After some searching I made a test application using solutions I found... but I can't get it working, I get a linker error.
If it's important: I'm using GCC 4.2.4 on a Linux.

Now some code...

main.c
  1. #include <stdio.h>
  2. #include "wrp.h"
  3.  
  4. int main(){
  5. printf("wrapper\n");
  6. wrp();
  7. }

wrp.h
  1. #ifdef __cplusplus
  2. extern "C"
  3. #endif
  4. void wrp();

cppcode.cpp
  1. #include <iostream>
  2. #include "wrp.h"
  3.  
  4. extern "C" void wrp(){
  5. std::cout << "wrapper zakonczyl dzialanie!\n";
  6. }

Linker error I get:
  1. /tmp/cc6Irctr.o: In function `main':
  2. main.c:(.text+0x1e): undefined reference to `wrp'
  3. collect2: ld returned 1 exit status

Command I use: gcc main.c -o test

Thanks in advance for Your help.
-Marek

PS. I don't know if this thread belongs to C or C++ forum.
Last edited by venomxxl; Jan 5th, 2009 at 12:47 pm.
Similar Threads
Reputation Points: 34
Solved Threads: 7
Junior Poster in Training
venomxxl is offline Offline
72 posts
since Jan 2009
Jan 5th, 2009
0

Re: Calling C++ function from C code

g++ -c cppcode.cpp
gcc -c main.c
g++ -o test main.o cppcode.o
Oh, and that might not work either.

This is how to mix C and C++
http://www.parashift.com/c++-faq-lit...c-and-cpp.html
In particular, the main() needs to be C++ so that global ctors/dtors get called.
Team Colleague
Reputation Points: 5862
Solved Threads: 950
Posting Sage
Salem is offline Offline
7,164 posts
since Dec 2005
Jan 5th, 2009
0

Re: Calling C++ function from C code

It worked! I can't believe it was so simple

Output:
  1. wrapper
  2. wrapper zakonczyl dzialanie!

Thanks a lot!
Reputation Points: 34
Solved Threads: 7
Junior Poster in Training
venomxxl is offline Offline
72 posts
since Jan 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: any one have idea about compiler control directives
Next Thread in C Forum Timeline: Unhandled exception and Access violation for every program





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC