Using C Headers in C++
I have searched the googles for this and have found that you use
extern "C" {
#include "header.h"
}
To include a C library inside of a C++ library... however, when I do this. The C++ program seems to pick up all my #defines and struct definitions but none of the function declarations leaving me with u开发者_JAVA百科ndefined reference to `function'.
Here is a minimal amount of src I am using.
json.h
//json.h
typedef struct json_object json_object;
struct json_object {
char key[15][50];
int size;
char value[15][50];
};
void json_parseText(char * text, struct json_object *jo);
test.cpp
//test.cpp
extern "C" {
#include "json.h"
}
int main() {
struct json_object jo;
char * keyVal;
char * text = "{ \"MsgType\": \"article\" }";
json_parseText(text, &jo);
}
g++ yields the following:
test.cpp:(.text+0x2c): undefined reference to `json_parseText'
notice that it is not complaining about the struct definition, so it seems like it got that from the header file. But not the function. This baffles me. I have never used C++ before now, but for my testing framework it must be in C++. Let me know if you have any thoughts on how to fix this. Thanks.
That's a link-time error. In other words, your C++ compiler picked your header all right; you just forgot to link with your library.
Right now, you tell your compiler that such functions and structures exist, but not where it can find them.
For a shared library (.so), you'll have to pass -l[lib name]
to G++; you might also have to specify additional folders in the library search path, as -l
requires a file name (without the extension) instead of a path. For a static library (.a), you'll have to include its path in the files to compile.
精彩评论