I have in my main.cpp this function:
double median(double values[], int count) {
int i, j, n = count, t;
for (i = 1 ; i <= n - 1 ; i++)
{
for (j = 1 ; j <= n - i ; j++)
{
if (values[j] <= values[j + 1])
{
t = (int) values[j];
values[j] = values[j + 1];
values[j + 1] = t;
}
}
}
if ( n % 2 == 0)
return (values[n / 2] + values[n / 2 + 1]) / 2.0 ;
else
return values[n / 2 + 1];
}
and I want to move that function into another file. So, I click on this function and then click F6 and then I write some name of the file eg. MathFunctions
and then I end up with:
MathFunctions.h:
#ifndef PROJECT_NAME_MATHFUNCTIONS_H
#define PROJECT_NAME_MATHFUNCTIONS_H
#endif //PROJECT_NAME_MATHFUNCTIONS_H
MathFunctions.cpp:
#include "MathFunctions.h"
double median(double values[], int count) {
int i, j, n = count, t;
for (i = 1 ; i <= n - 1 ; i++)
{
for (j = 1 ; j <= n - i ; j++)
{
if (values[j] <= values[j + 1])
{
t = (int) values[j];
values[j] = values[j + 1];
values[j + 1] = t;
}
}
}
if ( n % 2 == 0)
return (values[n / 2] + values[n / 2 + 1]) / 2.0 ;
else
return values[n / 2 + 1];
}
I'm a beginner in C++ and I don't understand why this is working like that. I'd rather expect it to put declarations of methods like:
double median(double values[], int count);
In *.h file and the interior of the method in *.cpp file and then include the *.h file in my main.cpp like that:
#include "MathFunctions.h"
Can someone explain me why this is working like that? What am I supposed to do with the files created by CLion? Should I include MathFunctions.cpp instead of header file in my main.cpp?
Unfortunately this is a CLion bug, tracked by https://youtrack.jetbrains.com/issue/CPP-9329, please create a Jetbrains account and vote for this issue.
I am not sure what you mean by "workaround". To make your code working, you need to
double median(double values[], int count);
in the MathFunctions.h
include file.main.cpp
, add #include "MathFunctions.h
as you mentionMathFunctions.cpp
to the list of source files for your executable.For example, assuming you have a CLion-created CMakeLists.txt, you should have something similar to
set(SOURCE_FILES main.cpp MathFunctions.cpp)
add_executable(foo ${SOURCE_FILES})
Some other random comments:
median()
is not a "method", it is a "function", or more precisely a "free-standing function" (that is, a function that is not part of a class).median()
is not really C++, is C, since it uses a low-level C array. You may want to use a std::vector<double>
instead.new
and delete
). Good luck in your journey!Edit
Changed link to Jetbrains bug to the first one reporting the issue.