1

I have built a project in CodeBlocks compiler.

I have created a file named main.cpp and a simple main() function in it.

I have run it and it works all OK! it prints "Hello World!".

Then I did create a new file named "test.cpp" and in it I put a test() function to print "GoodBye World!".

BUT when I run it, the main.cpp gets compiled. I use CodeBlocks compiler as already said.

What should I do to run the currently opened file? Or why it still uses main.cpp for execution?

Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105
  • Paste code of test.cpp – Ricky Jun 14 '14 at 04:41
  • 3
    Its all in the name: They don't call it `main()` for nothing. If you're expecting `test()` to execute just because it is the active document window, that's not how the language works. If that isn't what your question intended, it might need rephrasing. If it is, you need to refer to a [decent book on the C programming language](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) – WhozCraig Jun 14 '14 at 04:41
  • no You are true. I got the problem. But I have a question. All the files of a project gets executed in a single run&build? – Mostafa Talebi Jun 14 '14 at 04:48
  • No, all the files, properly configured in your project, get *compiled and linked*. Only `main()` runs out of the gate (initialization expressions no withstanding). Where you go from `main()` is at *your* behest. If you want `test()` to run, call it from `main()`. – WhozCraig Jun 14 '14 at 04:57

2 Answers2

2

The first function called in a C++ program is main(). The name of the file doesn't matter, so you could write a function with the signature main() in test.cpp. But, note that you can only define one function with the same name and arguments in the entire program, so you can't put it in both main.cpp and test.cpp.

Tyler
  • 1,818
  • 2
  • 13
  • 22
1

When you run another file in CodeBlocks it still runs the last executed file, and that's why main.cpp is getting compiled.

To run test.cpp you have to use ctrl+shift+f9 or under build tab click Compile current file

Compile Current File Codeblocks

  • It _should_ build the whole project, no? The problem was that the OP (five years ago!) didn't make the mental connection that it is `main()` that serves as the entrypoint of the program, regardless of filename or of which file was added to the project first. – Lightness Races in Orbit Feb 14 '19 at 18:26
  • It builds the file but I am not able to execute it afterwards. I even removed the file from the project, but it still runs. What is the problem here? – Prabhat Oct 02 '21 at 05:44