mardi 28 mars 2017

Confused about 'extern' and 'static extern' storage classes in C++11

I read over a few articles about this, and am taking a few introductory courses to C++ concurrently. All of the courses I am taking and these articles just don't help me understand how to implement the extern and static extern storage class. I don't feel comfortable moving on until I really have a grasp on this, even though what I am seeing from other programmers is that they do not use these storage classes, but use inheritance from a header file and local static storage class to use a static variable in a function. Both of those instances I can do. I figured out how to use the static storage class both within the same source file and also by inheriting the static variable from an inherited source file.

I keep getting linker and / or compiler errors.

I am using Visual Studio 2015 Community Edition with C++11, and have CodeDroid in Android with C++98.

Will someone please teach me how to use the extern and static extern storage classes without linker and compiler errors?

For example, say I had one.cpp and two.cpp. Say I have an int main() function in one.cpp. Say I want to demonstrate outputting the value of an extern int in the main() function. And, say I have a void function called extFuncExample() declared and defined in one.cpp, and also want to output its value there.

A course I am taking has extern and static extern as two different storage classes. So, if you would be so kind as to break this down to me, so I can output these values without compiler and linker errors.

Thank you so much!

one.cpp

    #include <iostream>
    #include "Two.cpp"


    int main()
    {
        extern int global_int;
        std::cout << "global_int = " << global_int << '\n';

        return 0;
    }

two.cpp

    #include <iostream>

    int global_int = 100;

This, I found works. I was including #include "two.cpp" in one.cpp and also using the extern storage class which was causing the issues. Removed #include "two.cpp" and it worked!

Aucun commentaire:

Enregistrer un commentaire