IT박스

유닉스 콘솔 / Mac 터미널에서 C / C ++를 컴파일하고 실행하는 방법은 무엇입니까?

itboxs 2020. 6. 30. 20:57
반응형

유닉스 콘솔 / Mac 터미널에서 C / C ++를 컴파일하고 실행하는 방법은 무엇입니까?


유닉스 콘솔이나 Mac 터미널에서 C 또는 C ++를 어떻게 컴파일 / 실행할 수 있습니까?

(알고 잊어 버렸다가 다시 배우십시오. 적어 두십시오.)


간단한 단일 소스 프로그램 인 경우 :

make foo

소스 파일은 foo.c 또는 foo.cpp 등입니다.

심지어 makefile이 필요하지 않습니다. Make에는 소스 파일을 확장명을 빼고 같은 이름의 실행 파일로 빌드하기에 충분한 기본 제공 규칙이 있습니다.

방금 빌드 한 실행 파일을 실행하는 것은 모든 프로그램을 실행하는 것과 동일하지만 셸은 $PATH실행 파일을 찾기 위해 찾은 내용 만 검색 하고 현재 디렉토리를 포함하지 않는 파일 만 검색하므로 실행 파일의 경로를 지정해야합니다 ( .).

그래서 내장 된 실행 파일을 실행합니다 foo:

./foo

gcc main.cpp -o main.out  
./main.out

이것은 모든 유닉스 컴퓨터에서 작동하는 명령입니다 ... Linux / Ubuntu에서는 사용하지만 OS X에서도 작동합니다. Terminal.app에 다음 명령을 입력하십시오 .

$ g++ -o lab21 iterative.cpp

-o 0이 아닌 문자 O

lab21 실행 파일이 될 것입니다

iterative.cpp 당신의 C ++ 파일입니까

해당 명령을 실행 한 후 터미널에서 다음을 입력하여 프로그램을 실행하십시오.

$ ./lab21

나를위한 두 단계 :

먼저:

make foo

그때:

./foo

Unix (Linux, Mac OS X, AIX 등) 환경에서의 모든 응용 프로그램 실행은 실행 가능한 검색 경로에 따라 다릅니다.

다음 명령을 사용하여 터미널에이 경로를 표시 할 수 있습니다.

에코 $ PATH

Mac OS X (기본적으로)에는 다음과 같이 콜론으로 구분 된 검색 경로가 표시됩니다.

/ usr / bin : / bin : / usr / sbin : / sbin : / usr / local / bin : / usr / X11 / bin

따라서 나열된 디렉토리의 모든 실행 파일은 이름을 입력하여 실행할 수 있습니다. 예를 들면 다음과 같습니다.

고양이 mytextfile.txt

/bin/catmytextfile.txt가 실행 되고 터미널에 표시됩니다.

실행 파일 검색 경로에없는 다른 명령을 실행하려면 실행 파일의 경로를 규정해야합니다. Mac OS XI의 홈 디렉토리에 MyProgram이라는 실행 파일이 있다고 가정하면 다음과 같이 완벽하게 규정 할 수 있습니다.

/ 사용자 / oliver / MyProgram

실행하려는 프로그램과 가까운 위치에 있으면 이름을 부분 경로로 한정 할 수 있습니다. 예를 들어, MyProgram디렉토리 /Users/oliver/MyProjectI에 있고 홈 디렉토리에 있으면 실행 파일 이름을 다음과 같이 규정하고 실행할 수 있습니다.

MyProject / MyProgram

또는 디렉토리에 /Users/oliver/MyProject2있고 실행을 원한다고 말하면 다음 /Users/oliver/MyProject/MyProgram과 같은 상대 경로를 사용하여 실행할 수 있습니다.

../MyProject/MyProgram

마찬가지로 MyProgram"현재 디렉토리"상대 경로를 사용해야하는 것과 동일한 디렉토리에있는 경우 . 현재 디렉토리는 마침표 뒤에 슬래시가 있습니다. 예를 들면 다음과 같습니다.

./MyProgram

현재 사용중인 디렉토리를 판별하려면 pwd명령 을 사용하십시오 .

일반적으로 프로그램 이름을 한정하지 않고 실행하려는 하드 디스크의 한 곳에 프로그램을 넣는 경우. 예를 들어, 다른 프로그램의 정기적으로 사용되는 쉘 스크립트에 대해 홈 디렉토리에 "bin"디렉토리가있는 경우 실행 가능 검색 경로를 변경하는 것이 좋습니다.

.bash_profile홈 디렉토리에서 기존 파일을 작성 또는 편집 하고 행을 추가하여 쉽게 수행 할 수 있습니다 .

#!/bin/sh
export PATH=$PATH:~/bin

Here the tilde (~) character is being used as a shortcut for /Users/oliver. Also note that the hash bang (#!) line needs to be the first line of the file (if it doesn't already exist). Note also that this technique requires that your login shell be bash (the default on Mac OS X and most Linux distributions). Also note that if you want your programs installed in ~/bin to be used in preference to system executables your should reorder the export statement as follows:

export PATH=~/bin:$PATH

Ryan, I am changing this to be an answer instead of a comment, since it appears I was too brief. Do all of this in "Terminal".

To use the G++ compiler, you need to do this:

  1. Navigate to the directory in which you stored the *.cpp file.

    cd ~/programs/myprograms/
    (the ~ is a shortcut for your home, i.e. /Users/Ryan/programs/myprograms/, replace with the location you actually used.)

  2. Compile it

    g++ input.cpp -o output.bin (output.bin can be anything with any extension, really. bin is just common on unix.)

    There should be NOTHING returned if it was successful, and that is okay. Generally you get returns on failures.

    However, if you type ls, you will see the list of files in the same directory. For example you would see the other folders, input.cpp and output.bin

  3. From inside the directory, now execute it with ./outbut.bin


Assuming the current directory is not in the path, the syntax is ./[name of the program].

For example ./a.out


Add following to get best warnings, you will not regret it. If you can, compile WISE (warning is error)

- Wall -pedantic -Weffc++ -Werror

A compact way to go about doing that could be:

make foo && ./$_

Nice to have a one-liner so you can just re-run your executable again easily.


To compile C or C++ programs, there is a common command:

  1. make filename

  2. ./filename

make will build your source file into an executable file with the same name. But if you want to use the standard way, You could use the gcc compiler to build C programs & g++ for c++

For C:

gcc filename.c

./a.out

For C++:

g++ filename.cpp

./a.out

Use a makefile. Even for very small (= one-file) projects, the effort is probably worth it because you can have several sets of compiler settings to test things. Debugging and deployment works much easier this way.

Read the make manual, it seems quite long at first glance but most sections you can just skim over. All in all it took me a few hours and made me much more productive.


I found this link with directions:

http://www.wesg.ca/2007/11/how-to-write-and-compile-c-programs-on-mac-os-x/

Basically you do:

gcc hello.c
./a.out (or with the output file of the first command)

just enter in the directory in which your c/cpp file is.

for compiling and running c code.

$gcc filename.c
$./a.out filename.c

for compiling and running c++ code.

$g++ filename.cpp
$./a.out filename.cpp

"$" is default mac terminal symbol


In order to compile and run a cpp source code from Mac terminal one needs to do the following:

  1. If the path of cpp file is somePath/fileName.cpp, first go the directory with path somePath
  2. To compile fileName.cpp, type c++ fileName.cpp -o fileName
  3. To run the program, type ./fileName

Running a .C file using the terminal is a two-step process. The first step is to type gcc in the terminal and drop the .C file to the terminal, and then press Enter:

username$ gcc /Desktop/test.c 

In the second step, run the following command:

username$ ~/a.out

참고URL : https://stackoverflow.com/questions/221185/how-to-compile-and-run-c-c-in-a-unix-console-mac-terminal

반응형