Why would the order of the parameters of compling produce warning?

Viewed 41

I was coding a very simply program which is basically hello world:

#include <string>
#include <vector>

int main() {
  std::vector<std::string> vec = {"Hello", "World"};
  for (const auto &num : vec) {
    std::cout << num << std::endl;
  }

  return 0;
}

Then I use a shell command to compile and execute the file:

echo "Start compling: "
g++ -std=c++11 -Werror -o test test.cpp
echo "File complied!"
echo "Start excuting: "
./test
echo "Program stopped"

In this way, everything is fine. But if I change the second command into:

g++ -std=c++11 -o -Werror test test.cpp

The compiler gives me such warnings ( which I treat as errors ) :

Start compling: 
/usr/bin/ld: test: _ZSt4cout: invalid version 2 (max 0)
/usr/bin/ld: test: error adding symbols: bad value
collect2: error: ld returned 1 exit status
File complied!
Start excuting: 
Hello
World
Program stopped

I really can't figure out why the order of the parameters would cause this.

1 Answers

The -o option takes an argument: the name of the output file. This is always the command line argument that immediately follows -o, even if it might otherwise look like an option.

So g++ -std=c++11 -o -Werror test test.cpp is writing the output to a file with the unusual name of -Werror, and using both test and test.cpp as input files. You can't use an executable as an input to compilation or linking and so it fails.

If you rearrange the command line arguments, make sure to keep -o test together.

Related