Emitting a global variable
Global variables have visibility of all the functions within a given module. LLVM provides the GlobalVariable
class to create global variables and set its properties such as linkage type, alignment, and so on. The Module
class has the method getOrInsertGlobal()
to create a global variable. It takes two arguments—the first is the name of the variable and the second is the data type of the variable.
As global variables are part of a module, we create global variables after creating the module. Insert the following code just after creating the module in toy.cpp
:
GlobalVariable *createGlob(IRBuilder<> &Builder, std::string Name) { ModuleOb->getOrInsertGlobal(Name, Builder.getInt32Ty()); GlobalVariable *gVar = ModuleOb->getNamedGlobal(Name); gVar->setLinkage(GlobalValue::CommonLinkage); gVar->setAlignment(4); return gVar; }
Linkage is what determines if multiple declarations of the same object refer to the same object, or to separate...