-
Multifile Programming
I am doing a multifile program. There are two files first.cpp and second.cpp that I would like to include in the main file main.cpp. I have first.h and second.h, that I include using
Code:
// in file main.cpp
#include "first.h"
#include "second.h"
The .h files look something like this:
Code:
// in files first.h and second.h
#ifndef __FIRST_H
#define __SECOND_H
int init(void);
#endif
And in the files first.cpp and second.cpp, I have added the lines
Code:
// in files first.cpp and second.cpp
#include "first.h"
#include "second.h"
I use the Turbo C++ 3.0 compiler. I have set the include directory to the directory that contains the .h and .cpp files. I can compile successfully, but I can't link it. The error message is 'Undefined symbol init() in module main.cpp'. Please help.
-
Put your header files into the directory you are compiling from.
-
first.h:
Code:
#ifndef FIRST_H
#define FIRST_H
void first(void);
#endif // FIRST_H
second.h:
Code:
#ifndef SECOND_H
#define SECOND_H
void second(void);
#endif // SECOND_HS
main.h:
Code:
#ifndef MAIN_H
#define MAIN_H
#include "first.h"
#include "second.h"
#endif //MAIN_H
first.cpp:
Code:
#include "first.h"
#include <iostream>
void first(void)
{
std::cout << "First" << std::endl;
}
second.cpp
Code:
#include "second.h"
#include <iostream>
void second(void)
{
std::cout << "Second" << std::endl;
}
main.cpp
Code:
#include "main.h"
int main()
{
first();
second();
}
First, compile first.cpp and second.cpp.
Then compile main.cpp, passing first.o and second.o as additional arguments to the command line (read your compiler's documentation for details on how the command line input should be formatted).
That's basically it.
-
Thanks
Thanks a lot, Sebastiani! Your solution saved me. Thanks goes to Lurker also.