Every time I click the 'run' or 'build and run' options in CodeBlocks for Mac OSX I get this dialogue:
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:
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?
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.