Search code examples
c++includeeffective-c++

Effective C++ (3rd edition) Item 4 code layout


In Scott Meyers' Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd edition), he describes in Item 4 how initialization of non-local static objects defined in different translation units crashes and gives a bunch of example codes.

However, I am confused with the code layout, what should it be?

What I have tried:

  • fileSystem.h
    #include <iostream>
    
    class FileSystem
    {
    public:
        std::size_t numDisks() const;
    };
    
  • fileSystem.cpp
    #include "fileSystem.h"
    
    std::size_t FileSystem::numDisks() const
    {
        return 1;
    }
    
    extern FileSystem tfs;
    
  • directory.h
    class Directory
    {
    public:
        Directory();
    };
    
  • directory.cpp
    #include <iostream>
    #include "fileSystem.h"
    #include "directory.h"
    
    Directory::Directory()
    {
        std::size_t disks = tfs.numDisks();
        std::cout << disks << std::endl;
    }
    Directory tempDir;
    int main()
    {
        return 0;
    }
    

And when executing g++ directory.cpp fileSystem.cpp, it turns out like this:

directory.cpp: In constructor ‘Directory::Directory()’:
directory.cpp:7:25: error: ‘tfs’ was not declared in this scope
    7 |     std::size_t disks = tfs.numDisks();
      |   

I am a little upset by #include stuff in C++, and I hope it would not prevent me from understanding the correct layout of the example code in Effective C++ Item 4.


Solution

  • You need to move extern FileSystem tfs; from fileSystem.cpp to the header file fileSystem.h to be able to compile it.

    If it's supposed to be possible to link it, you also need to define it in fileSystem.cpp.

    fileSystem.h

    extern FileSystem tfs;
    

    fileSystem.cpp

    FileSystem tfs;