Howto access CVars from code?

Hello!

I’ve been working with the examples given here: Console Variables in C++

But I’m still having a hard time wrapping my head around the usage of “FAutoConsoleVariableRef”.
I have two (actually more) classes from which I need to be able to determine the current value of a given CVar.

I’ve added the following code to lets say ‘weapon.cpp’:

static int32 DrawWeaponDebugLines = 0;
FAutoConsoleVariableRef CVARDrawWeaponDebugLines(TEXT("Game.DrawDebugWeapons"),DrawWeaponDebugLines,...);

I can now access the DrawWeaponDebugLines as expected and it updates when I change its value via the console at runtime, but of course only within ‘weapon.cpp’.

My thinking is, that whenever/wherever I ‘register’ a cvar, I should be able to ‘read’ it also from wherever and whenever, I want. Is this basic assumption correct?

In lets say ‘item.cpp’, Ive tried adding:

extern FAutoConsoleVariableRef CVARDrawWeaponDebugLines;
int32 MyVar = CVARDrawWeaponDebugLines->GetInt();

but that just gives me unresolved symbol errors at link time!
I’ve also tried using:

CVar = IConsoleManager::Get().FindConsoleVariable(TEXT("Game.DrawDebugWeapons"));"

but that always returns null/0 for CVar, as if I never registered the CVar (it does show up if I run the help command in the console, I can ‘browse’ to it and read my help text).

Am I totally misunderstanding something here? Most examples I’ve found just use CVars within the same cpp file, but surely this must be possible sowehow? Any suggestion? Thanks!

Instead of declaring the console variables in a source file, you could add some kind of container (be it a class, struct, or namespace) for them. Like this:

// Header file

class FCVars
{
public:
	static FAutoConsoleVariableRef DrawWeaponDebugLines;

private:
	static int32 DrawWeaponDebugLinesValue;
};


// Source file

int32 FCVars::DrawWeaponDebugLinesValue = 0;
FAutoConsoleVariableRef FCVars::DrawWeaponDebugLines(...);

I tested this just now by copying-pasting your CVar registration in one of my cpp files and placing the extern declaration into a different cpp file and I actually didn’t get any linker errors at all. It seemed at first glance like it should work and I think it should. Something else may be going on that is causing the linker error.