C++ equivalent of Java packages


Hi all, I’ve been writing a few simple programs using Notepad++ and the MinGW compiler (I’ve noticed that many people use an IDE of some kind, but I’ve deliberately avoided this to get a better understanding of how to build a program from the ground, up). Lately the file count of a particular program has been getting bigger and bigger (I’m up to a massive 7 files).

I would like to implement a few subfolders to separate the different files and keep things organized. Before starting C++ I studied a little bit of Java, at least enough to appreciate its package structure. I found it quite simple to implement and thought to do the same with my C++ source code. For example, I saved a class’ .h and .cpp file in a folder called “classes”, then I tried to implement the .h file in the Main function using a number of variations (not at the same time of course):

#include “classes.ClassName.h”
#include “classes/ClassName.h”

Note the dot in the first #include (similar to Java’s import statement) and the forward slash in the second #include. They didn’t work, and when I looked around, I found answers that were specific for coding in an IDE, which I’m not using at the moment.

I would really appreciate any suggestions about implementing subfolders manually, and using the setup outlined above (Notepad++ and MinGW).

Cheers!
I found answers that were specific for coding in an IDE

The format of the include statement shouldn't depend on whether you're using an IDE or not. It's a function of the compiler to interpret the include statement and locate the desired file. The compiler should look for include files relative to two locations. The default folder for main file and the compiler's path for library headers.

Since you're using Windows, the second #include should work. Just make sure that the classes folder is under your main source folder.


Maybe your compiling wrong? You could also try a back-slash.

given the folder structure
1
2
3
4
5
- my_program
    - my_classes
        my_class.cpp
        my_class.h
    main.cpp


and the files:
1
2
3
4
5
6
7
8
9
10
11
12
13
// my_class.h
#ifndef MYCLASS_H
#define MYCLASS_H

#include <iostream>

class My_Class
{
    public:
    My_Class(void);
};

#endif 

1
2
3
4
5
6
7
8
// my_class.cpp

#include "my_class.h"

My_Class::My_Class(void)
{
    std::cout << "hello from my class\n";
}

1
2
3
4
5
6
7
8
// main.cpp
#include "my_classes/my_class.h"  // or perhaps "my_classes\my_class.h"

int main(void)
{
    My_Class my_Class;
    return 0;
}


Your command line to compile would be: (assuming you are in the my_program folder)
g++ main.cpp my_classes/my_class.cpp -o program
Last edited on
Topic archived. No new replies allowed.