Question

i'm trying to create a library with some functions I often use, but compiling I have this error:

Torri_lib.cpp||multiple definition of `inizRandVett(int*, int, int, int)'|
Torri_lib.cpp||first defined here|
Torri_lib.cpp||multiple definition of `printVett(int*, int)'|
Torri_lib.cpp||first defined here|
Torri_lib.cpp||multiple definition of `scambio(int*, int*)'|
Torri_lib.cpp||first defined here|
||=== Build finished: 6 errors, 0 warnings (0 minutes, 0 seconds) ===|

This is the main.cpp:

#include <iostream>        
#include "Torri_lib.h"
#define N 10
using namespace std;

void ordina(int*,int);

int main()
{   int vett[N];
    srand(time(NULL));
    inizRandVett(vett,N,-20,20);
    printf("Vettore generato:\n");
    printVett(vett,N);
    ordina(vett,N);
    printf("\n\nVettore ordinato (neg a sx, pos a dx):\n");
    printVett(vett,N);
    printf("\n\n");
    return 0;
}
void ordina(int*vett,int dim)
{   int i,j,neg=0,pos=0;
    for(i=0;i<dim;i++)
        if(vett[i]<0)
           neg++;
        else
           pos++;
   for(i=0,j=neg;i<neg;i++)
        if(vett[i]>=0){
           while(vett[++j]>=0);
           scambio(&vett[i],&vett[j]);
        }
}

This is Torri_lib.cpp:

#include <iostream>
#include"Torri_lib.h"

void inizRandVett(int *vett, int dim, int rangeMin, int rangeMax)
{   int i;
    for(i=0;i<dim;i++)
       vett[i]=rand()%(rangeMax-rangeMin)+rangeMin;
}

void printVett(int *vett, int dim)
{  int i;
   for(i=0;i<dim;i++)
        printf("%d ",vett[i]);
}


void scambio(int*var1,int*var2)
{
    int temp=*var1;
    *var1=*var2;
    *var2=temp;
}

And this is Torri_lib.h :

void inizRandVett(int*, int, int, int );
void printVett(int *, int);
void scambio(int*,int*);

I don't understand why it says me this error, I don't see multiple definition of the functions. Can you help me? Thanks!

Was it helpful?

Solution 2

You need to write in header file to prevent multiple declaration:

#pragma once

// code

OR

#ifndef NAME_H_
# define NAME_H_

// code

#endif

OTHER TIPS

Maybe you didn't put a guard in your .h file?

Try putting at the beginning of the file:

#ifndef TORRI_H_INCLUDED
#define TORRI_H_INCLUDED

and at the end:

#endif
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top