Files available:

main.cpp :

 #include <iostream> #include "sqlite3/sqlite3.h" #include "global.h" #include "test.h" using namespace std; int main() { sqlite3_open16(L"blockchain2.db", &db_handler); __sqlite3_print__ test(); system("pause"); sqlite3_close(db_handler); return 1; } 

global.h :

 #pragma once #include "sqlite3/sqlite3.h" #define sqlite3_reset(stmt) sqlite3_reset(stmt), sqlite3_finalize(stmt) static sqlite3* db_handler; #define __sqlite3_print__ cout << db_handler << endl; 

test.h :

 #pragma once void test(); #include <iostream> #include "global.h" using namespace std; void test() { __sqlite3_print__ } 

What is wrong with this reptile?

What is wrong with this reptile? Why is the pointer from test.cpp empty?


such a result cannot be obtained with a single translation unit. And in your question it is only one - main.cpp. You actually have at least two broadcast units.

I didn’t quite understand what kind of translation units it says, if you are talking about displaying something, then there is a macro call in test.cpp.

I tried extern , but it turns out the same. Once again the whole code:

 // --------- main.cpp: #include <iostream> #include "sqlite3/sqlite3.h" #include "global.h" #include "test.h" using namespace std; int main() { sqlite3* db_handler; sqlite3_open16(L"sqlite3.db", &db_handler); __sqlite3_print__ test(); system("pause"); sqlite3_close(db_handler); return 1; } // --------- global.h: #pragma once #include "sqlite3/sqlite3.h" #define sqlite3_reset(stmt) sqlite3_reset(stmt), sqlite3_finalize(stmt) extern sqlite3* db_handler; #define __sqlite3_print__ cout << db_handler << endl; // --------- test.h: #pragma once void test(); // --------- test.cpp: #include <iostream> #include "global.h" #include "test.h" using namespace std; sqlite3* db_handler; void test() { __sqlite3_print__ } 
  • You are deceiving us. Such a result cannot be obtained with a single .cpp file. - AnT
  • The two versions of the code are fundamentally different. - AnT

1 answer 1

First, you most likely are deceiving us: it is impossible to get such a result with a single broadcast unit. And in your question it is only one - main.cpp . You actually have at least two broadcast units.

Secondly, and where is the global pointer here? static variable is a static variable, not a global variable. With this static you yourself "killed" the globality, i.e. they asked the compiler to create a separate variable for each translation unit.

In C ++ 17, you have an easy way to create global variables through a header file.

 inline sqlite3* db_handler; 

And in earlier versions of the C ++ standard and in C, you will have to do everything in the classic way. In the header file we declare

 extern sqlite3* db_handler; 

and in one of the implementation files we define

 sqlite3* db_handler;