How to create macro with git branch name?

Are you building on multiple platforms? If so, there may not be a single answer. On Windows, you’d probably need a Batch script to do it, and you might use sh or bash on macOS/Linux. Alternatively, you could ensure that your build machine has Python installed, and then use that.

This sort of thing is one reason that developers use tools like CMake. CMake is a scripting language as well as a build system, so it can be used to implement these sorts of custom behaviours.

In one project, I used the following setup to add a git hash to my builds (branch name could be achieved similarly):

git_hash.cpp.in

#include <git_hash.hpp>

char const* git::hash = "@GIT_HASH@";
char const* git::version = "@PROJECT_VERSION@";

git_hash.hpp

#pragma once

namespace git {
extern char const *hash;
extern char const *version;
} // namespace git

CMakeLists.txt

add_library(git_version_info STATIC)

find_package(Git)

# https://stackoverflow.com/a/21028226
execute_process(COMMAND
  "${GIT_EXECUTABLE}" describe --match=NeVeRmAtCh --always --abbrev=40 --dirty
  WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}"
  OUTPUT_VARIABLE GIT_HASH
  ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)

configure_file("${CMAKE_CURRENT_SOURCE_DIR}/git_hash.cpp.in"
    "${CMAKE_CURRENT_BINARY_DIR}/git_hash.cpp" @ONLY)

target_sources(git_version_info PRIVATE
    "${CMAKE_CURRENT_BINARY_DIR}/git_hash.cpp"
    git_hash.hpp)

target_include_directories(git_version_info PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")

target_compile_features(git_version_info PUBLIC cxx_std_17)

set_target_properties(git_version_info PROPERTIES
    POSITION_INDEPENDENT_CODE TRUE
    VISIBILITY_INLINES_HIDDEN TRUE
    C_VISIBILITY_PRESET hidden
    CXX_VISIBILITY_PRESET hidden)

This creates a static library that just defines git and project info strings. This library can be linked into targets that require this information.