简体   繁体   中英

Why declare global variables in file doesn't include? (c++)

An unexpected result occurred when testing both Windows-VS-environment and Linux-Cmake-environment.

A global variable was declared, even though it is not in included file.

Here is Example codes.


CmakeLists.txt

ADD_EXECUTABLE( app.out main.cpp test.cpp )

main.cpp

int main()
{
    return 0;
}

test.h

#pragma once

#include <iostream>

class Test
{
public:
    Test();
};

test.cpp

#include "Test.h"

static Test g_test;

Test::Test() {
    std::cout << "Construct Test\n";
}

What I expected just return 0 at main

actual result print Construct Test

Why this happening?

The short answer here is, simply, because this is how C++ works.

static Test g_test;

This instantiates an object of type Test in the test.cpp translation unit. Whether or not it is declared in some header file is immaterial. It is instantiated. So it exists. You are alive because you, yourself exist and not because your name is recorded in some birth certificate, somewhere.

All objects that get instantiated get constructed. Full stop. No exceptions. This is how C++ works on its basic fundamental level (they also get destroyed at some point, by the way, in the ordinary ebb and flow of program execution).

So, when you link your program with the compiled test.cpp module, your final application has whatever's in test.cpp . Which includes that object that gets instantiated in global scope.

Whether the object's declared in some header file that gets compiled is completely irrelevant. As long as the object exists, it gets constructed. Whether or not an object gets constructed does not depend on it being declared in the header file. It gets constructed by the virtue of its existence. All that a declaration in some header file does is exactly that: a declaration. An assertion that something exists. Somewhere. The compiler doesn't care. If the declaration is for an object the compiler now knows that it exists, somewhere, and it trusts that one of the cpp s that get compiled will instantiate this object. If not, you get a link failure, at some point.

All compliant C++ implementations work this way, whether it's Linux, Windows, or anything else. This is a fundamental part of C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM