how to initialize a global variable while declaring in linux environment.

This topic contains 1 reply, has 2 voices, and was last updated by  oliverernster 3 years ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #31785


    I am working in linux environment

    I am trying to declare a global variable, and that global variable is allocated in memory..
    But i want to initialize that global variable while declaring itself, and i tried, that variable is being allocated,but it was not initialized with the value provided.
    How can i initialize the global variable while declaring itself.
    help me out.

    I tried in this way..
    //global variable
    volatile int x =10;
    int y;

    y =x;



    x variable= undefined value (‘X’)
    y variable = undefined value (‘X’)

    when I try to write the “x” variable value into the memory location, i cannot see the value “10” .

    Do I need to take an extra care while initializing the global variables while declaring itself.

    IF I initialize the global variable in any one of the functions it is working properly.
    //global variable
    volatile int x ;
    int y;

    x =15;


    x variable =15;
    y variable =15;

    Thanks in advance. 🙂



    Firstly, are you sure you want the variable to be global? Global variables are bad in general and can usually be avoided. If you really need it in this file then consider the use of static instead but I’d avoid that too if at all possible.
    Alternatively, you could declare it extern in the header and define it in the file as a global, though not volatile. Why do you want it to be volatile anyhow; this is not clear.

    Secondly, I don’t think the fact that you are using Linux is particularly relevant; it’s the language use you should be worried about.

    I recommend taking a look at

    In particular, note that
    “Operations on volatile variables are not atomic, nor do they establish a proper happens-before relationship for threading. This is according to the relevant standards (C, C++, POSIX, WIN32),[2] and this is the matter of fact for the vast majority of current implementations. Thus, the usage of volatile keyword as a portable synchronization mechanism is discouraged by many C/C++ groups.[3][4][5]”

    If you are working in a multithreaded environment then consider declaring a variable and changing it using a synchronisation mechanism rather than using the volatile keyword. Mutexes might be an alternative you could use in linux for this.

    Kind regards

Viewing 2 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic.