1.10. More complex compilation — many output binaries

Assuming we want to do print greetings as we did with Building with two files, but in multiple languages, we can use a common main.c and use language specific file instead of file greeting.c.

1.10.1. The files

main.c and greeting.h remains the same:

main.c
#include "greeting.h"

int main() {
    greeting();
    return 0;
}
greeting.h
#ifndef GREETING_H
#define GREETING_H

void greeting(void);

#endif /* GREETING_H */

But now we have language specific greeting files:

greeting_en.c — English
#include <stdio.h>
#include "greeting.h"

void greeting() {
    printf ("Hello World!\n");
}
greeting_fr.c — French
#include <stdio.h>
#include "greeting.h"

void greeting() {
    printf ("Bonjour le monde!\n");
}
greeting_es.c — Spanish
#include <stdio.h>
#include "greeting.h"

void greeting() {
    printf ("Hola Mundo!\n");
}

1.10.2. Compilation only for English

To compile only English language specific file with GCC, the commands would be.

gcc main.c greeting_en.c -Wall -o greeting_en

As we did earlier, to execute the binary generated from the source file, the command would be:

./greeting_en

If everything went fine, the output would be:

Hello World!

1.10.3. Compilation for all languages

To compile them at the same time for all languages with GCC, the commands would be.

gcc main.c greeting_en.c -Wall -o greeting_en
gcc main.c greeting_fr.c -Wall -o greeting_fr
gcc main.c greeting_es.c -Wall -o greeting_es

We can as well run all the generated binaries:

./greeting_en
./greeting_fr
./greeting_es

If everything went fine, the output would be:

Hello World!
Bonjour le monde!
Hola Mundo!

Here, we used a common files main.c, greeting.h and isolated language specific stuff in other files greeting_en.c, greeting_fr.c and greeting_es.c

1.10.4. Compilation using cl.exe

To compile on windows with Microsoft Visual C Compiler cl.exe, the command would be

cl.exe main.c greeting_en.c /W4 /nologo /Fegreeting_en.exe
cl.exe main.c greeting_fr.c /W4 /nologo /Fegreeting_fr.exe
cl.exe main.c greeting_es.c /W4 /nologo /Fegreeting_es.exe

As seen in previous chapters, the compilation output would be very similar:

main.c
greeting_en.c
Generating Code...
main.c
greeting_fr.c
Generating Code...
main.c
greeting_es.c
Generating Code...

To run all the generated binaries, we can run them as follows:

call greeting_en.exe
call greeting_fr.exe
call greeting_es.exe

The output would be same as that we would have got when compiled with gcc:

Hello World!
Bonjour le monde!
Hola Mundo!