ibmemcached Linking Error: undefined reference to `memcached_exist' - c++

I am trying to write a sample code using libmemcached c/c++ client version (0.53)
gcc -o test test.c -I/home/libmemcached/include -L/home/libmemcached/lib -lmemcached -lmemcachedutil
However i get an error
/tmp/ccoaToYP.o: In function main':
test.c:(.text+0x255): undefined reference tomemcached_exist'
Has anyone come across this issue ? I cannot use version higher than 0.53 (basically any 1.0) due to limitation with installed gcc. I see that this command was added for 0.53.
Also, The path and ld_library_path are straightforward too.
PATH is set with /bin:/sbin:/usr/bin:/usr/sbin:/usr/bin/X11:/usr/sbin.
LD_LIBRARY_PATH is set with /home/libmemcached/lib:/usr/lib:/usr/lib64:/lib
$ nm libmemcached.so | grep -i memcached_exist
00014bc2 T _Z15memcached_existP12memcached_stPKcj
00014b06 T _Z22memcached_exist_by_keyP12memcached_stPKcjS2_j
$
If i comment out the memcached_exist call, rest of code compiles and executes just fine.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <libmemcached/memcached.h>
int main(int argc, char *argv[])
{
memcached_server_st *servers = NULL;
memcached_st *memc;
memcached_return rc;
char *key= "keystring";
char *value= "keyvalue";
uint32_t flags;
char return_key[MEMCACHED_MAX_KEY];
size_t return_key_length;
char *return_value;
size_t return_value_length;
memc= memcached_create(NULL);
servers= memcached_server_list_append(servers, "localhost", 11211, &rc);
rc= memcached_server_push(memc, servers);
if (rc == MEMCACHED_SUCCESS)
fprintf(stderr,"Added server successfully\n");
else
fprintf(stderr,"Couldn't add server: %s\n",memcached_strerror(memc, rc));
rc= memcached_set(memc, key, strlen(key), value, strlen(value), (time_t)0, (uint32_t)0);
if (rc == MEMCACHED_SUCCESS)
fprintf(stderr,"Key stored successfully\n");
else
fprintf(stderr,"Couldn't store key: %s\n",memcached_strerror(memc, rc));
return_value= memcached_get(memc, key, strlen(key), &return_value_length, &flags, &rc);
if (rc == MEMCACHED_SUCCESS)
{
fprintf(stderr,"Key %s returned %s\n",key, return_value);
}
rc = memcached_exist(memc, key, strlen(key));
fprintf(stderr," Error Code: %s\n",memcached_strerror(memc, rc));
return 0;
}
Thanks
Antony

If you don't want to compile as C++, you can always call the mangled name directly. If you want this code to be reusable and to be able to upgrade the libraries easily, etc, you shouldn't do that. For a more extensible solution, I'll add to H2CO3's answer.
If you want to for some reason keep all your main source compiled as C, you can create a .cpp file that has stubs that call the C++ library functions. For example:
// libraries.cpp
//
// (includes needed to memcached lib call and types)
extern "C" memcached_return memcached_exist(memcached_st *memc, char *key, size_t len)
{
return memcached_exist(memc, key, len);
}
Then you can compile libraries.cpp and link against the memcached libs using g++ to a libraries.o and link against that on your gcc line.

Name mangling. The shared object file contains mangled C++ function (method?) names, while your code is compiled as C, containing the non-mangled name memcached_exist. Try compiling your file as C++.

Related

Lua: Cant open shared library when lua is wrapped in C++

EDIT: Nearly got the answer, I just dont completely understand it, see last paragraph.
I try to build a shared lua library and use it within a larger project. When calling the script which loads the shared library from shell everything works. However, when I wrap the script within another shell, I get a runtime error when loading the library. Dependent on the script it is just any call to a lua function from c (i.e. lua_pushnumber). Here is a minimal example.
totestlib.cpp:
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
int init(lua_State *L) {
lua_toboolean(L, -1);
return 0;
}
static const struct luaL_Reg testlib[] = {
{"init", init},
{NULL, NULL}
};
extern "C"
int luaopen_libtotestlib(lua_State *L) {
luaL_newlib(L, testlib);
return 1;
}
Compiled with: g++ -shared -fPIC -I./lua-5.4.4/src -L./lua-5.4.4/src totestlib.cpp -o libtotestlib.so
testlib.lua (testing shared library):
testlib.lua
print("start")
testlib = require("libtotestlib")
print("done")
testlib.init(true)
print("called")
Calling the lua script using ./lua-5.4.4/src/lua testlib.lua works. Everything is printed. Wrapping script in the following c++ code does not work:
call_testlib.cpp
extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#include <unistd.h>
static lua_State *L;
int main(int argc, char *argv[]) {
L = luaL_newstate();
luaL_openlibs(L);
int tmp = luaL_loadfile(L, "testlib.lua");
if(tmp != 0) {
return 1;
}
tmp = lua_pcall(L, 0, 0, 0);
if(tmp != 0) {
printf("error pcall\n");
return 1;
}
}
Compiled with g++ call_testlib.cpp -o ./call_testlib -I./lua-5.4.4/src -L./lua-5.4.4/src -llua it prints "error pcall". If I print the error message on the lua stack, I get:
string error loading module 'libtotestlib' from file './libtotestlib.so':
./libtotestlib.so: undefined symbol: luaL_checkversion_
In this case the undefined symbol is luaL_checkversion_ (which I dont call myself), but with other scripts it is usually the first lua_... function that I call.
I have tried several things to fix this. For example, linking -llua when compiling the shared library, but this does not work (and should not be the problem as calling the script itself works). I also tried to load preload the library from c++ (as done in this question) instead of from lua, but I guess it does not really make a difference and I am getting the same error. I also uninstalled all lua versions from my path to make sure I always use the same version.
What is the difference between calling the script directly from shell and calling it inside a c function? Am I doing something wrong?
EDIT: Nearly got the answer. When using MYCFLAGS= -fPIC when compiling lua I can link lua to the shared library. At least this one works, but does not seem like a good solution to me and does not really answer my question: Why can lua itself (from shell) somehow add these symbols to the library while the wrapped c version can not? Additionally, my program has lua once linked in the shared library and once in the compiled C++ project (not optimal imo).

cannot find -lC:\SQLAPI\lib\sqlapi.lib in omnet++ IDE

I am running my simple C++ program in OMNET ++ IDE
My code is as follows
**#include <stdio.h> // for printf
#include <string.h>
#include <SQLAPI.h> // main SQLAPI++ header
//#include <asaAPI.h>
int main(int argc, char* argv[])
{
SAConnection con;
con.setOption( "UseAPI" ) = "DB-Library";
con.setClient( SA_SQLServer_Client );
try
{
con.Connect(
"paper2"
"NADRA",
"",
SA_SQLServer_Client);
printf("We are connected!\n");
// Disconnect is optional
// autodisconnect will occur in destructor if needed
//con.Disconnect();
printf("We are disconnected!\n");
}
catch(SAException &x)
{
// SAConnection::Rollback()
// can also throw an exception
// (if a network error for example),
// we will be ready
try
{
// on error rollback changes
//con.Rollback();
}
catch(SAException &)
{
}
// print error message
printf("%s\n", (const char*)x.ErrText());
}
return 0;
}**
I have already linked all the files but the error that i am getting is as follow
c:/mingw/bin/../lib/gcc/mingw32/6.3.0/../../../../mingw32/bin/ld.exe: cannot find -lC:\SQLAPI\lib\sqlapi.lib
collect2.exe: error: ld returned 1 exit status
Where as the file sqlapi.lib is in the same folder but linker is not able to find it. Can someone tells me about the issue that why compiler is not able to link it .I am using MINGW as a C++ compiler. The screen shot is attached by with the question about the linked filesenter image description here
If you are using -l, then it should be followed by the library name only, so something like:
-lsqlapi
If you want to specify a search path, then:
-lsqlapi -LC:\SQLAPI\lib\
(Usually the path is in Linux mode, so `C:/SQLAPI/lib though).
Then if this doesn't work, you can always force the library to be linked by just using it as another object:
C:/SQLAPI/lib/sqlapi.lib
Note though that gcc doesn't link against Visual Studio static libraries, which sqlapi might (because of the extension being .lib and not .a, but then this may be the export library for a dll).

Local dynamic library

Right off the bat, I want to say that I've never worked with dynamic libraries so It's possible that I don't even understand how they work properly.
I want to have a fully loaded code running and after some trigger (probably user interaction) I want to load a specific library and execute a function inside that library. Preferably close it afterwards. Essentially allowing me to change it and re-load it during run time.
This is the simple dynamic library (called dynlib.so located in the same directory as the main code):
int getInt(int arg_0)
{
return (arg_0 + 7);
}
And this is the main program:
#include <iostream>
#include <dlfcn.h>
int main() {
void *lib_handle = dlopen("./dynlib.so", RTLD_LAZY | RTLD_NOW);
if (!lib_handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
typedef int (*func_ptr)(int);
func_ptr func = (func_ptr)dlsym(lib_handle, "getInt");
std::cout << func(13);
dlclose(lib_handle);
}
I'm compiling it using: g++ -std=c++11 -ldl loadlibtest.cpp -o main.
The error I'm catching is ./libshared.so: file too short In my if (!lib_handle) {.
It works fine for me. I've compiled dynlib.so with
$ gcc dynlib.c -fPIC -shared -o dynlib.so
(Obviously, you need to either compile it as C or C++ with extern "C" to avoid name mangling).
and I needed to place -ldl after the source file in the g++ invocation.
gcc: 4.8.5; g++: 5.3.0
dlsym may fail too and casting from void* to function pointers is technically UB. You should base it on the usage snippet from the
manpage(modified for your function):
dlerror(); /* Clear any existing error */
/* Writing: func = (int (*)(int)) dlsym(handle, "getInt");
would seem more natural, but the C99 standard leaves
casting from "void *" to a function pointer undefined.
The assignment used below is the POSIX.1-2003 (Technical
Corrigendum 1) workaround; see the Rationale for the
POSIX specification of dlsym(). */
*(void **) (&func) = dlsym(handle, "getInt");
if ((error = dlerror()) != NULL) {
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
After some great replies I discovered what I'm doing wrong.
1) I wasn't using extern "C" for my library functions, so dlsym was unable to find the function.
2) I didn't know that dynamic libraries had to be compiled << pretty stupid of me.
I still want to know if there is a way to use uncompiled code as a library, but my initial problem was solved, thanks to everyone.

Using C Code in C++ Project

I want to use this C code in my C++ project :
mysql.c :
/* Simple C program that connects to MySQL Database server*/
#include <mysql.h>
#include <stdio.h>
#include <string.h>
main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
char *password = "rebourne"; /* set me first */
char *database = "mydb";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
if (mysql_query(conn, "show tables")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
/* output table name */
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
it compiles with gcc :
gcc -o output-file $(mysql_config --cflags) mysql.c $(mysql_config --libs)
but not with g++ ..
What would you do ?
edit :
The Error is :
exit(1); was not declared in this Scope
First things first: it would probably be a lot more helpful if you showed us the compilation errors.
That being said, my initial instinct is to suggest:
extern "C"
{
#include <mysql.h>
#include <stdio.h>
#include <string.h>
}
This is a guess right now, but without the actual error messages it's the best you're going to get.
Oh, and perhaps renaming the file to end in .cpp, .c++ or .C (uppercase) would help.
use :
extern "C"
{
YOUR CODE HERE
}
OK, now that the answer is given there are a few lessons to learn.
First, always provide the errors when you're reporting things that don't compile. Those messages contain valuable information. Don't paraphrase them either. Cut and paste them in their own code block.
Second, any time you use a function, check the docs. I have never seen C documentation that didn't tell you the required header file up at the top of the man page or equivalent. It's as much a part of the documentation as explaining what the function does. There is a myriad of headers required in programming C and C++. Documenting the required headers for functions is a very common documentation idiom as a result.
#include <stdlib.h>
Though I doubt that it has really said "exit(1);". Please show exact messages next time.
Now, I haven't programmed C in a long while (and was never at a very high level) but I find it odd that you would want to include a main() function into an already existing code base. Is it really the compiler, or the linker, that's complaining? And when you say that GCC succeeds in compiling the code, are you only compiling that one source file, or including it in a bigger code base as well?
If my guess is correct, it would make sense for you to rename the function to something other than main, e.g. connect_to_database().

How do I load a shared object in C++?

I have a shared object (a so - the Linux equivalent of a Windows dll) that I'd like to import and use with my test code.
I'm sure it's not this simple ;) but this is the sort of thing I'd like to do..
#include "headerforClassFromBlah.h"
int main()
{
load( "blah.so" );
ClassFromBlah a;
a.DoSomething();
}
I assume that this is a really basic question but I can't find anything that jumps out at me searching the web.
There are two ways of loading shared objects in C++
For either of these methods you would always need the header file for the object you want to use. The header will contain the definitions of the classes or objects you want to use in your code.
Statically:
#include "blah.h"
int main()
{
ClassFromBlah a;
a.DoSomething();
}
gcc yourfile.cpp -lblah
Dynamically (In Linux):
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
int main(int argc, char **argv) {
void *handle;
double (*cosine)(double);
char *error;
handle = dlopen ("libm.so", RTLD_LAZY);
if (!handle) {
fprintf (stderr, "%s\n", dlerror());
exit(1);
}
dlerror(); /* Clear any existing error */
cosine = dlsym(handle, "cos");
if ((error = dlerror()) != NULL) {
fprintf (stderr, "%s\n", error);
exit(1);
}
printf ("%f\n", (*cosine)(2.0));
dlclose(handle);
return 0;
}
*Stolen from dlopen Linux man page
The process under windows or any other platform is the same, just replace dlopen with the platforms version of dynamic symbol searching.
For the dynamic method to work, all symbols you want to import/export must have extern'd C linkage.
There are some words Here about when to use static and when to use dynamic linking.
It depends on the platform. To do it at runtime, on Linux, you use dlopen, on windows, you use LoadLibrary.
To do it at compile time, on windows you export the function name using dllexport and dllimport. On linux, gcc exports all public symbols so you can just link to it normally and call the function. In both cases, typically this requires you to have the name of the symbol in a header file that you then #include, then you link to the library using the facilities of your compiler.
You need to #include any headers associated with the shared library to get the declrarations of things like ClassFromBlah. You then need to link against the the .so - exactly how you do this depends on your compiler and general instalation, but for g++ something like:
g++ myfile.cpp -lblah
will probably work.
It is -l that link the archive file like libblah.a or if you add -PIC to gcc you will get a 'shared Object' file libblah.so (it is the linker that builds it).
I had a SUN once and have build this types of files.
The files can have a revision number that must be exact or higher (The code can have changed due to a bug). but the call with parameters must be the same like the output.