Search code examples
c++g++header-files

How do you define a "Hello World" function in a seperate file in c++


and I apologize for asking a very basic question, but basically, I'm not able to wrap my head around include "fileImade.h"

I'm trying to write a main function, that's something like

int main()
{
int x = 5;
int y x 6;
std::cout << add(x, y) << std::endl;
}

where add() is defined in a separate .cpp file, and #include -ed in this one, (I'm doing this because I'm getting the point where my code is getting impractically large to do in a single file.), but my understanding is that you need a header file to... Glue your other files together, or I guess mortar them if the files are the bricks, but I absolutely cannot figure out how to make this work for the life of me.

(while using g++), should I tag -I? According to me googling, yes, according to my compiler output, no.

Should I write a header file and a .cpp files for the add() function? Apparantly, yes, or no, if I choose to write both files in the command line before the -o.

Should I include a forward declaration of the function in my main.cpp file? Again, according to the internet, yes, though that's not working terribly well for me.

So to my question: Can someone show me a main() function that calls a hello world() function in a separate file?

I'm honestly at my wits' end with this because all the guides seem to be on defining classes in header files, which, while useful, is a bit beyond the scope of what I'm attempting right now.

Thank you in advance for reading, and any advice offered.


Solution

  • The logic of the file separation may be imagined as:

    (single file program)

    /// DECLARATION of all functions needed in the main
    int add(int x, int y); // declaration of add
    
    ///
    int main()
    {
        std::cout << add(2, 3) << std::endl;
        return 0;
    }
    
    /// IMPLEMENTATION of all functions needed in the main
    int add(int x, int y)
    {
        return x + y;
    }
    

    The next you have to do is move all declarations to the headers and implementations to the cpps:

    (separated files program)

    /// add.h
    #ifndef ADD_H /// https://en.wikipedia.org/wiki/Include_guard
    #define ADD_H
    int add(int x, int y);
    #endif
    
    /// main.cpp
    #include "add.h"
    
    int main()
    {
        std::cout << add(2, 3) << std::endl;
        return 0;
    }
    
    /// add.cpp
    #include "add.h"
    
    int add(int x, int y)
    {
        return x + y;
    }