Search code examples
c++pointersstaticsqliteunresolved-external

How to define static pointer to sqlite3 struct? c++


I want to have static pointer to sqlite3 struct, so I could open the connection to DB once, execute some queries in runtime and close the DB connection at the program exit.

(I linked sqlite3 static lib, dll)

so in my class header:

foo.h:

#include "sqlite/sqlite3.h"

class foo
{
    public:
       static sqlite3 *db;
       static void connect();
}

foo.cpp:

#include "foo.h"

sqlite3 foo::*db = nullptr;

foo::connect(){

   //sqlite3 *db;   //<-this works
   char *zErrMsg = 0;
   int rc;

   rc = sqlite3_open("test.db", &db);

   if( rc ){
      fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
      exit(0);
   }else{
      fprintf(stderr, "Opened database successfully\n");
   }
   //sqlite3_close(db); // close connection when program is exiting. Not here.

}

I get this error: LNK2001: unresolved external symbol "public static struct sqlite3 *foo::db" ....


Solution

  • You have a pointer to an sqlite3, so the right definition syntax would be

    sqlite3* foo::db = nullptr;
    

    or just

    sqlite3* foo::db;
    

    Note that you have to make it point to a valid sqlite3 object before de-referencing it.