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); ...

Get LLVM Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.