1

I have created a small library (around 600 lines) in C++ in Codeblocks and I'm using OMP and O3 optimization to build it. When I try to build the same code through the terminal with a Makefile with exactly the same options (-fopenmp -O3) it runs around 3 times slower. I need to build it in various machines so I need to do the process through a terminal and not through Codeblocks. Why is this happening? This is my Makefile if you're interested:

CC=g++ 
CFLAGS= 
LDFLAGS= -fopenmp -O3 -std=c++11 
SOURCES=main.cpp CNNFunctions.cpp     
OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=cnn

all: $(SOURCES) $(EXECUTABLE) 

$(EXECUTABLE): $(OBJECTS) 
    $(CC) $(LDFLAGS) $(OBJECTS) -o $@

.cpp.o: 
    $(CC) $(CFLAGS) $< -o $@
pap-x
  • 564
  • 1
  • 8
  • 15

2 Answers2

5

Because, contrary to your claim, you're not building it with the exact same options.

Your CFLAGS are empty, and those are the flags you're using for the compilation. You cannot resolve that by the time you get to the linking step.

  • So I need to put the flags in CFLAGS too? – pap-x Aug 20 '14 at 07:48
  • @pap-x Not only that, you don't need to have then in `LDFLAGS`, so you could simply move them. (Edit: actually, `-fopenmp` might be needed at link-time too, but at least `-std=c++11` and `-O3` don't need to be.) –  Aug 20 '14 at 07:49
  • Yes I had tried to move them to CFLAGS and it didn't work. It needs to be in both. – pap-x Aug 20 '14 at 07:54
5

Your Makefile is wrong. The optimization flags are relevant mostly at compile time. Try at least:

CXX=g++ 
CXXFLAGS=  -Wall -fopenmp -O3 -std=c++11 -mtune=native
LDFLAGS= -fopenmp
SOURCES=main.cpp CNNFunctions.cpp     
OBJECTS=$(SOURCES:.cpp=.o) 
EXECUTABLE=cnn

all: $(SOURCES) $(EXECUTABLE) 

$(EXECUTABLE): $(OBJECTS) 
       $(LINK.cpp) $(OBJECTS) -o $@

Optimization might matter at link time for Link-Time Optimization, for that use CXX=g++ -flto and LDFLAGS=$(CXXFLAGS)

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • That's what I initially thought too, but `-fopenmp` is documented as implying `-pthread`, and `-pthread` is also needed at link time. A quick test shows that `-fopenmp` does indeed have an effect at link time. –  Aug 20 '14 at 07:52