cppdev
cppdev

Reputation: 6973

How local constants are stored in c++ library files

I am writing a library where I need to use some constant integers. I have declared constant int as a local variable in my c function e.g. const int test = 45325;

Now I want to hide this constant variable. What it means is, if I share this library as a .so with someone, he should not be able to find out this constant value ? Is it possible to hide constant integers defined inside a library ? Please help

Here is my sample code

int doSomething() {

const int abc = 23456;
int def = abc + 123;

}

doSomething is defined as local function in my cpp file. I am referring this constant for some calculations inside the same function.

Upvotes: 0

Views: 700

Answers (4)

Damon
Damon

Reputation: 70136

If I understand right, you're not so much worried about an exported symbol (since it's a plain normal local variable, I'd not worry about that anyway), but about anyone finding out that constant at all (probably because it is an encryption key or a magic constant for a license check, or something the like).

This is something that is, in principle, impossible. Someone who has the binary code (which is necessarily the case in a library) can figure it out if he wants to. You can make it somewhat harder by calculating this value in an obscure way (but be aware of compiler optimizations), but even so this only makes it trivially harder for someone who wants to find out. It will just mean that someone won't see "mov eax, 45325" in the disassembly right away, but it probably won't keep someone busy for more than a few minutes either way.

Upvotes: 2

Simon Richter
Simon Richter

Reputation: 29578

The constant will always be contained in the library in some form, even if it is as instructions to load it into a register, for the simple reason that the library needs it at runtime to work with it.

If this is meant as some sort of a secret key, there is no good way to protect it inside the library (in fact, the harder you make it, the more people will consider it a sport to find it).

Upvotes: 1

CashCow
CashCow

Reputation: 31435

You can declare it as

extern const int test;

and then have it actually defined in a compilation unit somewhere (.cpp file).

You could also use a function to obtain the value.

Upvotes: 0

AndersK
AndersK

Reputation: 36082

The simplest is probably to just do a wrapper class for them

struct Constants
{
   static int test();
...

then you can hide the constant in the .cpp file

Upvotes: 0

Related Questions