Header files -- multiple definition

I get multiple definition of getSquareSides().

main.cpp
1
2
3
4
5
6
7
8
#include <iostream>
#include "square.h"

int main() {
	std::cout << "a square has " << getSquareSides() << "sides" << std::endl;
	std::cout << "a square of length 5 has perimenter" << getSquarePerimeter(5) << std::endl;
	return 0;
}


square.h
1
2
3
4
5
#ifndef SQUARE_H
#define SQUARE_H
int getSquareSides() { return 4; }
int getSquarePerimeter(int);
#endif 


square.cpp
1
2
3
4
5
#include "square.h"

int getSquarePerimeter(int sideLength) {
	return sideLength * getSquareSides();
}
Always put implementations in .c or .cpp files.
1
2
3
4
5
6
7
8
#ifndef SQUARE_H
#define SQUARE_H

    // make it inline http://en.cppreference.com/w/cpp/language/inline
    inline int getSquareSides() { return 4; } // constexpr 
    
    int getSquarePerimeter(int);
#endif  
closed account (E0p9LyTq)
Declaring a function inline in a header file also works.

1
2
3
4
5
6
7
#ifndef SQUARE_H
#define SQUARE_H

inline int getSquareSides() { return 4; }
int getSquarePerimeter(int);

#endif 
Topic archived. No new replies allowed.