Answers/Solutions to Exercises in Chapter 6, Exercise 7

E7: We have a C program in two separate source files. In the first we define a global buffer char mybuf[100];. In
the other source file we declare mybuf as external, i.e. extern char* mybuf;. When we compile and link our program
using a C compiler, the program works correctly, while when we compile and link it using a C++ compiler, the program will not work correctly. Do you have any explanation?

A7: It has to do with typing. C is weakly typed and so the compiler considers char mybuf[100]and  to be identical types. Thus it will make the connection and links mybuf   from the first file with mybuf from the second file (and that was what we intended), so everything works fine. However, C++ is strongly typed, and for the C++ compiler char mybuf[100] and char* mybuf are of distinct types and will not be linked. Thus mybuf in the first file and mybuf in the second file are two different variables, with all the problems it brings.

Back to Answers/Solutions Index                          Back to Answers/Solutions for Chapter 6 Index