4

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.

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, the first option works :). How could one execute the above option 1 in just one line?
g++ -o myprog source.cpp source.c
Doesn't this compile the c source as c++?
I don't think so as the .c will tell the compiler to do the right thing.
3

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.)

Comments

0

you can't do that, you can compile C code with gcc, and then link it with c++ objects with g++, referring to the symbols defined in the C objects via the extern keyword, but you can't do the opposite

1 Comment

It not only possible, it's very frequently used. That is why functions in header system header files are declared as extern "C". The only things you can't export this way are classes and objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.