file.h
template
void tfunc( T a)
{
.........
}
file1.cpp
#include"file.h"
void myfunc1()
{
tfunc(123);
}
file2.cpp
#include"file.h"
void myfunc2()
{
tfunc(456);
}
main.cpp
extern void myfunc1();
extern void myfunc2();
int main()
{
myfunc1();
myfunc2();
return 0;
}
Compile with:
g++ -o main.exe file1.cpp file2.cpp main.cpp
Before you compile, just try answering below questions:
1. Will this compile?
If Yes then Why and how?
If no then you are on right track. Same thing happens with normal function definition. But hold on, c++ template handles this multiple definition problem very smoothly. It means above files will compile and execute properly.
Thats special handling with multiple template instantiation done by linker.
Now you know that this answer of above questions is yes, so you may want to know how and why?
Will post in next post. This question was asked to my friend in NetApp.
template
void tfunc( T a)
{
.........
}
file1.cpp
#include"file.h"
void myfunc1()
{
tfunc(123);
}
file2.cpp
#include"file.h"
void myfunc2()
{
tfunc(456);
}
main.cpp
extern void myfunc1();
extern void myfunc2();
int main()
{
myfunc1();
myfunc2();
return 0;
}
Compile with:
g++ -o main.exe file1.cpp file2.cpp main.cpp
Before you compile, just try answering below questions:
1. Will this compile?
If Yes then Why and how?
If no then you are on right track. Same thing happens with normal function definition. But hold on, c++ template handles this multiple definition problem very smoothly. It means above files will compile and execute properly.
Thats special handling with multiple template instantiation done by linker.
Now you know that this answer of above questions is yes, so you may want to know how and why?
Will post in next post. This question was asked to my friend in NetApp.
Comments
Post a Comment