Error breaking a c ++ program into .h, .cpp, and main.cpp files

2

I have sliced a moyenne.cpp program that makes the average of a c ++ rating vector in three: main.cpp , moyenne.cpp and moyenne.h .

The file only works, but today the program tells me when it did g++ main.cpp -o main that:

In function 'main':
main.cpp:(.text+0x196): undefined reference to 'moyenne(std::vector<double, std::allocator<double> > const&)'

However, it is used in main.cpp

#ifndef MOYENNE_H_INCLUDED
#define MOYENNE_H_INCLUDED

#include<vector>

double moyenne(std::vector<double>const& tableau);

and the same "includes" in moyenne.cpp.

update

When I did g++ moyenne.cpp -o moyenne I have a similar error:

$ g++ moyenne.cpp -o moyenne
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function '_start':
(.text+0x20): undefined reference to 'main'
collect2: error: ld returned 1 exit status

Then I do not understand where this undefined reference is ...

    
asked by ThePassenger 13.04.2017 в 15:25
source

1 answer

0

You have 2 source files, so you have to use different options to generate the executable:

g++ -c moyenne.cpp -o moyenne

Notice the -c . With this, we tell the compiler that is not a final executable, but an object file .

To generate the final executable, after of the previous order, we make

g++ -o test main.c moyenne.o

When using multiple files, each of them is an independent object , but if we do not indicate it, the compiler will search for main( ) in any source file that Let's tell him.

In addition, each object file has no real knowledge of what is in others. That's a separate compile operation, called linked (link). It is during this linked that the references to the functions are searched, and the appropriate pointers are established.

    
answered by 15.04.2017 / 12:31
source