1

I have a global variable that I'm trying to share between multiple .cpp files. From what I understand in C++, if I want to access a global variable I need to declare it as extern (source)

In test.h:

#pragma once

#include <string>
#include <python3.6m/Python.h>
#include <boost169/boost/python.hpp>

using namespace std;

extern string mystr;
void setString(string s);

test.cpp

#include "test.h"

using namespace std;
using namespace boost::python;

void setString(string s){
    mystr = s;
}
BOOST_PYTHON_MODULE(Test){
    def("setString", &setString);
}

cls.cpp (the file that includes a class)

#include "test.h"

#include <python3.6m/Python.h>
#include <boost169/boost/python.hpp>
using namespace std;
using namespace boost::python;

class MyTest{
public:
    MyTest(){
    }
    void printString(){
        cout << mystr;
    }
};

BOOST_PYTHON_MODULE(Cls){
    class_<MyTest, MyTest*>("MyTest", init<>())
    .def("printString", &MyTest::printString);
}

the Makefile:

CC   = g++ -O3 -std=c++11
FLAGS    = -g -c -Wall
LIBS = -lpython3.6m -lboost_python3
LIBDIR = -L /lib64 -L /lib64/boost169
PY3 = -I/usr/include/python3.6m

cls.o:cls.cpp
    $(CC) -fPIC $(PY3) cls.cpp -c $(LIBS)

Cls.so:cls.o
    $(CC) $(LIBDIR) -shared cls.o -o Cls.so $(LIBS)

test.o:test.cpp
    $(CC) -fPIC $(PY3) test.cpp -c $(LIBS)

Test.so:test.o
    $(CC) $(LIBDIR) -shared test.o -o Test.so $(LIBS)

and finally, in the python file:

from Test import *
from Cls import *

And this gives an error:

File "test/test.py", line 1, in <module>
    from Test import *
ImportError: test/Test.so: undefined symbol: mystr

I have tried to move the string mystr to test.cpp as suggested in this post :

// in test.cpp
string mystr;

// in cls.cpp
extern string mystr;

(of course I removed the extern in the header file)

How can I share the global variables? They do not need to be accessed from python since they are only supposed to be used by the C++ modules

Thanks

qwerty_99
  • 640
  • 5
  • 20

0 Answers0