I want to pass an array from one cpp file to another.

first:

void wrapper(float **A,int N){

    N=2;
    printf("Allocating Matrices\n");
    *A = (float*)malloc(N*N*sizeof(float));

    for(int i = 0; i < N; ++i){
      for (int j=0;j<N;j++){
         *A[j+i*N] = i;

      }
    }

  for(int i = 0; i < N; ++i) {
      for (int j=0;j<N;j++){
         printf("\nA_from=%f",*A[j+i*N]);

      }
      printf("\n");

}

}

second:

extern void wrapper(float **A,int N);


int main () {


    int N=2;
    float* A;

    wrapper(&A,N);

    for(int i = 0; i < N; ++i){
      for (int j=0;j<N;j++){
         printf("\nA_to=%f",A[j+i*N]);
      }
      printf("\n");
    }

   return 0;
}

I am compiling:

g++ -c -g first.cpp
g++ -c -g second.cpp
g++ -o run first.o second.o

and I am receiving:

multiple definition of `wrapper(float**, int)'
at first file

Recommended Answers

All 2 Replies

Well you code compiles and links for me with exactly the commands you have given with the sole addition of #includes of cstdio and cstdlib to the top of your source files.

Also note that the array subscription operator has a higher preceedence than pointer indirection * so *A[j+i*N] is interpreted as as *(A[j+i*N]) which causes your program to exhibit undefined behaviour because I suspect you actually intended (*A)[j+i*N], which you can achieve by typing exactly that.

Yes!It was the pointer preceedence!
Now ,with (A)[j+iN] it works fine!
Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.