5

if you have something like this:

int _tmain(int argc, _TCHAR* argv[]) {
    int i;
#if (num>99)
    i = func();
#else
    i= func2();
#endif
    return 0;
}

static int func()
{
    return 1;
}
static int func2()
{
    return 2;
}

Is it reasonable to expect that depending on if num is bigger or smaller then 99 ether func or func2 will be removed from the runtime code?

Or would I rather need to also embed the functions in an #if to achieve this goal?

dragosht
  • 3,237
  • 2
  • 23
  • 32
lsteinme
  • 750
  • 1
  • 6
  • 20
  • 6
    "The runtime code" isn't part of the C standard, so the C standard cannot answer this question. It is a matter of how your linker operates. Dead code removal is certainly a known and used optimization strategy that is available on many platforms. – Kerrek SB Feb 11 '15 at 09:23

3 Answers3

2

This depends on linker,what does it with dead code is linker specific. You should also include function definition under #if to make sure that it wont results into machine code.

Vagish
  • 2,520
  • 19
  • 32
1

It depends on optimization level. On linux you can check it youself using readelf -s ./a.out | grep func2

But I think you use windows, so you need some similar tool http://www.pe-explorer.com/ for example.

Here is list of tools: Any tool/software in windows for viewing ELF file format?

Community
  • 1
  • 1
KonK
  • 290
  • 1
  • 8
1

You would need to embed the function definitions also in an #if to achieve the goal.

code may be something like this:

Let's say the variable "num" is getting populated form configuration.

int _tmain(int argc, _TCHAR* argv[]) {
    int i;
#if (num>99)
    i = func();
#else
    i= func2();
#endif
    return 0;
}

#if(num>99)
static int func()
{
    return 1;
}
#else
static int func2()
{
    return 2;
}
#endif

Hope it helps. Thank you!

Rabinarayan Sahu
  • 156
  • 1
  • 1
  • 7