Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with wrapping a C++ code

Tags:

c++

c

To try the C++ code wrapping within C, I used the following: header.h

#ifdef __cplusplus
extern "C"
#endif
void func();

source.cpp

#include "header.h" 
#include <iostream>
extern "C" void func()
{
std::cout << "This is C++ code!" << std::endl;
}

and source.c

#include "header.h"
int main()
{
func();
}

To compile and link, I used the following sequence:

g++ -c source.cpp
gcc source.c source.o -o myprog

The error I get is: ence to std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' source.cpp:(.text+0x1c): undefined reference tostd::basic_ostream >::operator<<(std::basic_ostream >& (*)(std::basic_ostream >&))' source.o: In function __static_initialization_and_destruction_0(int, int)': source.cpp:(.text+0x45): undefined reference tostd::ios_base::Init::Init()' source.cpp:(.text+0x4a): undefined reference to std::ios_base::Init::~Init()' source.o:(.eh_frame+0x12): undefined reference to__gxx_personality_v0' collect2: ld returned 1 exit status

How can I make this simple code compile and run? It should serve as a basis for my future development.

like image 246
user506901 Avatar asked Feb 22 '23 13:02

user506901


2 Answers

Link with g++ as well:

g++ -c source.cpp
g++ source.c source.o -o myprog

Or better:

g++ -c source.cpp -o source_cpp.o
gcc -c source.c -o source_c.o
g++ -o myprog source_cpp.o source_c.o

Best to avoid the common prefix source.{cpp,c} as it causes confusion.

like image 186
trojanfoe Avatar answered Mar 03 '23 12:03

trojanfoe


You'll still have to link with the C++ linker:

gcc -o source-c.o source.c
g++ -o source-p.o source.cpp
g++ -o myprog source-c.o source-p.o

Your C++ object file will need to resolve symbols from the C++ library, which only the C++ linker will pull in automatically. (Alternatively, you could specify the library manually for the C linker.)

like image 21
Kerrek SB Avatar answered Mar 03 '23 14:03

Kerrek SB