Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

eyalroz/cpp-static-block

Open more actions menu

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
7 Commits
 
 
 
 

Repository files navigation

A static block implementation for C++

This is a single-header-file repository which allows for writing static blocks in C++. That is: Blocks of code, outside of any function, which can't be called from a function, and are executed once when the program starts (before main()).

C++ doesn't support this natively. But with a little bit of preprocessor trickery and some compiler features, it can effectively be done.

This is similar to Java's static (initialization) blocks.

Example of use

#include <iostream>
#include "static_block.hpp"

static_block {
    std::cout << "In the static block!" << std::endl;
}

int main() {
    std::cout << "In main()." << std::endl;
}

Notes

  • Static blocks participate in the static initialization order fiasco, so be careful not to create dependence loops with othe static code (e.g. construction of global objects, other wtiatc bocl
  • Based on my answer to this StackOverflow question.
  • This is C++98 code (!)
  • It's possible to use multiple static blocks in the same file.
  • Static blocks can't be nested, and cannot be used within classes and structs.

About

A static block implementation for C++

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages

Morty Proxy This is a proxified and sanitized view of the page, visit original site.