This is a mirror of official site: http://jasper-net.blogspot.com/

Using the Visual C/C++ Compiler (2)

| Sunday, April 8, 2012
Introduction

This time I will have a look at function level linking. Again I show a bit what is going on in the background and how enabling or disabling this functionality will affect the generated code

Background

I assume the reader to be familiar with the basics of the Visual C/C++ compiler. Also the reader should not be affraid of using the compiler from the command line.

Function Level Linking

Looking at the small code sample below we would expect the linker to throw away the sub function as it is not used by the code at all.

// sample.cpp

int add(int a, int b) {
   return a + b;
}

int sub(int a, int b) {
   return a - b;
}

int main() {
   int c;
   c = add(2, 4);
}

Unfortunately this will not happen. Because the main task of a linker is to combine sections of same type (e.g. code sections) and thereby resolve externals.

The compiler cannot help in this situation either. It compiles each unit of source code one by one. Once it has compiled a file of source code to an object file it completely forgets about it. Thus it cannot throw away a function just because it is not used in the source code file being compiled. The function might be used (later) by another translation unit which declares it extern.

So when calling the Visual C/C++ compiler this way

   cl /FAs sample.cpp /link /entry:main /nodefaultlib /map

we see it generate code for the sub function.

0001:00000000   ?add@@YAHHH@Z   0000000140001000 f   sample.obj
0001:00000020   ?sub@@YAHHH@Z   0000000140001020 f   sample.obj
0001:00000040   main            0000000140001040 f   sample.obj

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-net

0 comments: