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 no开发者_如何学Got 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().
精彩评论