plz double check - is this correct way

Unintended consequences for this setup or am farming the function out correctly?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 fx.h
 *
 *  Created on: Jan 29, 2017
 *      

#ifndef FX_H_
#define FX_H_

int add (int x,int y)
{
	return x+y;
}



#endif /* FX_H_ */ 


1
2
3
4
5
6
7
8
9
10

#include <iostream>
#include "fx.h"
using namespace std;

int main() {
	int result = add(300, 900);
	cout<<"result = "<<result;
	return 0;
}
Last edited on
No, this isn't correct. It will cause problems any time "fx.h" is used in more than one source file, since add is not inline. It violates the "One Definition Rule."

http://en.cppreference.com/w/cpp/language/definition#One_Definition_Rule

There are two ways to fix this. One is to move the definition of add into its own source file (likely "fx.cpp") while leaving a declaration in "fx.h".

1
2
3
4
5
6
7
// fx.h
#ifndef FX_H_
#define FX_H_

int add (int x,int y);

#endif 

1
2
3
4
5
 //fx.cpp
#include "fx.h"
int add(int x, inty) {
    return x + y;
}



The other is to give the function internal linkage:
1
2
3
4
5
6
7
8
9
10
// fx.h
#ifndef FX_H_
#define FX_H_

inline int add (int x,int y)
{
	return x+y;
}

#endif 
Thanx !

In regard to the top fx.h/fx.cpp I don't know what to do with the fx.cpp

Is fx.cpp the "main.cpp"; or - is it in addition to the main.cpp? I've often been confused about whether to have multiple .cpps in a project.

In that example how do I integrate fx.h, fx.cpp into main.cpp?
Last edited on
Is fx.cpp the "main.cpp"; or - is it in addition to the main.cpp? I've often been confused about whether to have multiple .cpps in a project.

It would be in addition to other source files in the project.


In that example how do I integrate fx.h, fx.cpp into main.cpp?

Assuming you're using an IDE, just add fx.cpp to your project. If you're using the command line, you would also compile fx.cpp and link the resulting object file.
It seems you dont have to include .cpp files though? Right. Also, which of the two solutions which you recommend? Ive been working with both.

Thanks. Awesome reply.
It seems you dont have to include .cpp files though? Right.

If you're talking about the #include system, no - you should not #include them.

Also, which of the two solutions which you recommend? Ive been working with both.

I tend to favor the separate cpp solution, both because it hides unnecessary details and reduces overall compile time, although for a very simple function like this I'd probably go with the inline solution.
Topic archived. No new replies allowed.