Question

Every time I click the 'run' or 'build and run' options in CodeBlocks for Mac OSX I get this dialogue:

enter image description here

I've checked Project > Properties > Build targets, which is what some forum posts said I should do, and all the files are checked but I keep getting the same popup.

This is my build log:

-------------- Build: Release in printarray (compiler: GNU GCC Compiler)---------------

g++  -o bin/Release/printarray obj/Release/arrays.o obj/Release/main.o  -s  
ld: warning: option -s is obsolete and being ignored
ld: duplicate symbol _anMyArray in obj/Release/main.o and obj/Release/arrays.o for architecture x86_64
collect2: ld returned 1 exit status


and these are my build messages:

enter image description here


These are the files, though I'm not sure if the content has anything to do with the problem (I made sure both Debug and Release were checked when I created the header and function definitions):

main.cpp

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

int main()
{
    using namespace std;

    PrintArray(anMyArray);

    return 0;
}


arrays.cpp

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

void PrintArray(int anArray[])
{
    using namespace std;

    int nElements = sizeof(anArray) / sizeof(anArray[0]);
    for (int nIndex=0; nIndex < nElements; nIndex++)
        cout << anArray[nIndex] << endl;
}


arrays.h

#ifndef ARRAYS_H
#define ARRAYS_H

int anMyArray[9] = { 4, 6, 7, 3, 8, 2, 1, 9, 5 };

void PrintArray(int anArray[]);

#endif // ARRAYS_H

Any help?

Was it helpful?

Solution

It's because you define the variable anArray in the header file. When its included in two translation units it's defined twice, giving you the duplicate symbol error.

Just declare it in the header file

extern int anMyArray[9];

and define it in one (and only one) source file.

OTHER TIPS

You declare anMyArray in your header file and then include it in both your cpp files, which means your variable is getting declared twice because of header expansion.

Move it to your main.cpp file.

I solved this question by the way below Settings->Complier...->Toolchain executables and click the button "Auto-detect" click "ok" the problem solved

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