Skip to content

Instantly share code, notes, and snippets.

@2bbb
Created July 26, 2017 17:03
Show Gist options
  • Save 2bbb/14411d9b184e2d4db7f0abaaf3d3240b to your computer and use it in GitHub Desktop.
Save 2bbb/14411d9b184e2d4db7f0abaaf3d3240b to your computer and use it in GitHub Desktop.
variable_inliner
#!/bin/bash
clang++ -c -std=c++11 -stdlib=libc++ main.cpp
clang++ -c -std=c++11 -stdlib=libc++ sub.cpp
clang++ main.o sub.o -o main
#pragma once
#include "variable_inliner.hpp"
namespace test_ns {
struct custom {
int x;
};
namespace {
custom &c = bbb::variable_inliner<custom>::get();
};
};
#include <iostream>
#include "constant.hpp"
#include "sub.hpp"
int main(int argc, char *argv[]) {
std::cout << "main 1: " << test_ns::c.x << std::endl;
test_ns::c.x = 1;
std::cout << "main 2: " << test_ns::c.x << std::endl;
sub_func();
std::cout << "main after sub: " << test_ns::c.x << std::endl;
}
#include <iostream>
#include "constant.hpp"
#include "sub.hpp"
void sub_func() {
std::cout << "sub 1: " << test_ns::c.x << std::endl;
test_ns::c.x = 2;
std::cout << "sub 2: " << test_ns::c.x << std::endl;
}
#pragma once
void sub_func();
#pragma once
namespace bbb {
template <typename variable_type, typename tag = variable_type>
struct variable_inliner {
static variable_type &get() {
static variable_type _;
return _;
};
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment