Reputation: 1520
Say I wish to use C++ STL containers in the implementation of a library that I want C programs to link to...
My example header is
/* mynums.h */
#ifndef MY_NUMS
#define MY_NUMS
#ifdef __cplusplus
extern "C" {
#endif
void append_num(int num);
void print_nums();
#ifdef __cplusplus
}
#endif
#endif
And my example implementation file is
/* mynums.cpp */
#include "mynums.h"
#include <vector>
using std::vector;
vector<int> nums;
void append_num(int num)
{
nums.push_back(num);
}
void print_nums()
{
for (int i = 0; i < nums.size(); i++)
{
printf("%d, ", nums[i]);
}
printf("\n");
}
My application looks like
/* app.c */
#include "mynums.h"
int main()
{
append_num(1);
append_num(2);
append_num(3);
print_nums();
return 0;
}
And my commands to compile these are
# Compiles and runs
g++ -c -fpic -shared -std=c++0x -o libmynums.so mynums.cpp
g++ -L. -lmynums -o app app.c
# Library compiles, but the application fails
g++ -c -fpic -shared -std=c++0x -o libmynums.so mynums.cpp
gcc -L. -lmynums -o app app.c
The errors I get when I try the second set of compilation commands are those very long stl errors we're oh-so familiar with. One example is
./libmynums.so" In function 'void std:vector<int, std::allocator<int> >::_M_emplace_back_aux<int const&>(int const &)':
mynums.cpp:(.text._ZNSt6vectorIiSaIiEE19_M_emplace_back_auxIIRKiEEEvDpOT_[_ZNSt6vectorIiSaIiEE19_M_emplace_back_auxIIRKiEEEvDpOT_]+0x15d): undefined reference to '__cxa-begin_catch'
I want to be able to compile and link my example application code to the shared object library using gcc. Is this possible? If so, then what changes are necessary to my provided code / commands?
Upvotes: 9
Views: 1174
Reputation: 223699
The problem is that you're not actually creating a shared library. You're creating an object file and naming it as if it were a shared library.
The -c
option to gcc/g++ means to perform the compilation stage only. This results in libmynums.so
being an object file. This is why you're able to link to it via g++ but not gcc.
Remove the -c
option when compiling mynums.cpp
and you'll get a shared library.
Upvotes: 9