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
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
std::basic_ostream >::operator<<(std::basic_ostream >& (*)(std::basic_ostream >&))'
source.cpp:(.text+0x1c): undefined reference to
source.o: In function __static_initialization_and_destruction_0(int, int)':
std::ios_base::Init::Init()'
source.cpp:(.text+0x45): undefined reference to
source.cpp:(.text+0x4a): undefined reference to std::ios_base::Init::~Init()'
__gxx_personality_v0'
source.o:(.eh_frame+0x12): undefined reference to
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.
Answer
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.
No comments:
Post a Comment