How to use an enum across files in C++?

In C++, enums can be used across files.

To use an enumeration in multiple files, you need to place the enumeration definition in a header file and include that header file in the files where the enumeration is needed.

For example, let’s say we have a header file called colors.h that defines an enum.

// colors.h

enum Color {
    RED,
    GREEN,
    BLUE
};

Then in another source file, we can include that header file and use the enum.

// main.cpp

#include "colors.h"
#include <iostream>

int main() {
    Color color = RED;
    
    if (color == GREEN) {
        std::cout << "The color is green" << std::endl;
    } else {
        std::cout << "The color is not green" << std::endl;
    }
    
    return 0;
}

In this example, we have included the colors.h header file in main.cpp and used the Color enum type in the main function.

Be sure to include the appropriate header files in both the header file where the enum is defined and in the source file where the enum is used. This ensures that the enum is resolved before being used.

In addition, you can also use namespaces to organize the definition of enums and avoid naming conflicts. For example:

// colors.h

namespace MyColors {
    enum Color {
        RED,
        GREEN,
        BLUE
    };
}

Then in the file where the enum is used, the enum can be referenced using a namespace.

// main.cpp

#include "colors.h"
#include <iostream>

int main() {
    MyColors::Color color = MyColors::RED;
    
    if (color == MyColors::GREEN) {
        std::cout << "The color is green" << std::endl;
    } else {
        std::cout << "The color is not green" << std::endl;
    }
    
    return 0;
}
bannerAds