-
Multiple Modules
I am trying to create a large program using multiple modules. I have the main source module that contains all of my function prototypes and the 'main' function, as well as my include files for <iostream> ect... and three sub modules where all of my other functions are defined (the ones that are prototyped in the main module). How do I get all the modules to link together? I have an #include directive at the top of each sub module with the filename for the main module in quotes, but that causes all kinds of compiler errors (mostly multiple function definitions).
I guess what I am asking is this : What directives do I need at the top of each sub module to get everything to link together and what is the syntax? I have looked through a few tutorials and books with no luck yet.
-
-
Forgive me if I am having trouble understanding, this is a new concept for me.
Should I then save my main module as a '.h' file in the header library and put a
'#include "mainmodule" 'directive at the top of each sub module?
Everything I try gives me a compiler error :
"in function main : multiple definition of 'main'"
-
Code:
// this is module.h
#ifndef MODULE_H_INCLUDED
#define MODULE_H_INCLUDED
void myfunc ( void );
#endif
Code:
// this is module.cpp
#include "module.h"
void myfunc ( void ) {
}
You repeat the above as many times as necessary for however many modules you want to create.
When you want to use it (anywhere, not just in main), do
Code:
// this is main.cpp
#include "module.h"
int main ( ) {
myfunc();
}
Such an example would be compiled with
gcc module.cpp main.cpp
Or add both .cpp files to the project, if you're using an IDE.
This is pretty much what the FAQ says.
-
OK, That makes more sense when you put it that way.
Two more questions:
1) I am getting a multiple definition error of a struct but it is only defined in one spot ( the main.cpp module ). I tried putting it in the header file but got the same error. The struct needs to be global so that all the modules can access it.
2) the struct contains only variables, no functions. Should I leave it as a struct or change it to a class?
Thanks again for all the help, I know I am getting slightly annoying :P
BTW, I am using DEV-C++. I understand that it is an IDE?
-
Sounds to me like you're #including .cpp files inside one another.
This in a header file
Code:
struct foo {
int someMember;
};
extern foo myVar;
This in ONE .cpp file
-
OK, Thanks! That was the problem... I did not declare the struct as extern.