What i did wrong to create toolbarButton with the following code?

I want to create two or three toolbarButton on the top of my maincomponent window. When I click the button, it can open a small window which contains a textEditor(I can input some values).
Here are my codes:
This is MainComponent.h

This is MainComponent.cpp

This is the myToolBar.h

#pragma once
#ifndef MYTOOLBAR_H
#define MYTOOLBAR_H
#include “…/JuceLibraryCode/JuceHeader.h”

ToolbarButton* button1;
ToolbarButton* button2;
bool flagButton1 = false;
class myToolBarFactory : public ToolbarItemFactory
{
public:
myToolBarFactory() {}
~myToolBarFactory() {}
enum itemIds
{
button1 = 1,
button2 = 2,
};

void getAllToolbarItemIds(Array <int>& ids)
{
	ids.add(button1);
	ids.add(button2);
	ids.add(separatorBarId);
	ids.add(spacerId);
	ids.add(flexibleSpacerId);
}

void getDefaultItemSet(Array <int>& ids)
{
	ids.add(separatorBarId);
	ids.add(flexibleSpacerId);
	ids.add(flexibleSpacerId);
	ids.add(separatorBarId);
	ids.add(button1);
	ids.add(separatorBarId);
	ids.add(button2);
	ids.add(separatorBarId);
}

ToolbarItemComponent* createItem(int itemId)
{
	switch (itemId)
	{
	case button1:

	case button2:

	default:
		break;
	}
	return 0;
}

};
myToolBarFactory factory;

class MyTextEditorListener : public Button::Listener
{
void buttonStateChanged(Button& button)
{
flagButton1 = true;
}
};
MyTextEditorListener* button1Listener;

class myToolBar : public Component,
public Button::Listener
{
public:
myToolBar()
:toolbar(0)
{
addAndMakeVisible(toolbar = new Toolbar());
toolbar->addDefaultItems(factory);

	button1->addListener(button1Listener);

}
~myToolBar()
{
	deleteAndZero(toolbar);
}
void resized()
{
	toolbar->setBounds(0, 0, getWidth(), 30);
}
void buttonClicked(Button* buttonThatWasClicked)
{
	if (buttonThatWasClicked == button1)
	{

	}
	if (buttonThatWasClicked == button2)
	{

	}
}

private:
Toolbar* toolbar;
};

#endif // !MYTOOLBAR_H

It pointed out the button1, button2, button1listener,and factory had already defined in MainComponent.obj when i use the window debugger.
Thanks in advance if anyone can give some advice.

During compilation each .cpp will be compiled into a .obj file (translation unit) then the linker will link these together. If it finds the definition of the same thing in multiple translation units it will moan essentially saying how am I suppose to know which one you want. Having just one definition is known as the one definition rule.

I suspect the easiest way to stop the linker moaning is add = nullptr; at the end of all those globals, but it’s not the right way!

Instead work to get rid of the globals (globals are generally a big no no) and also I suggest you split your declaration and definition into separate files, i.e. have a MyToolBar.h and MyToolBar.cpp

I’ll just also add too that you don’t need both pragma once and #ifndef ... they do the same thing.

1 Like

Thank you so much, i will follow your advice.:smile: