Make file executable mac os

Makefile для самых маленьких

Не очень строгий перевод материала mrbook.org/tutorials/make Мне в свое время очень не хватило подобной методички для понимания базовых вещей о make. Думаю, будет хоть кому-нибудь интересно. Хотя эта технология и отмирает, но все равно используется в очень многих проектах. Кармы на хаб «Переводы» не хватило, как только появится возможность — добавлю и туда. Добавил в Переводы. Если есть ошибки в оформлении, то прошу указать на них. Буду исправлять.

Статья будет интересная прежде всего изучающим программирование на C/C++ в UNIX-подобных системах от самых корней, без использования IDE.

Компилировать проект ручками — занятие весьма утомительное, особенно когда исходных файлов становится больше одного, и для каждого из них надо каждый раз набивать команды компиляции и линковки. Но не все так плохо. Сейчас мы будем учиться создавать и использовать Мейкфайлы. Makefile — это набор инструкций для программы make, которая помогает собирать программный проект буквально в одно касание.

Для практики понадобится создать микроскопический проект а-ля Hello World из четырех файлов в одном каталоге:

Все скопом можно скачать отсюда
Автор использовал язык C++, знать который совсем не обязательно, и компилятор g++ из gcc. Любой другой компилятор скорее всего тоже подойдет. Файлы слегка подправлены, чтобы собирались gcc 4.7.1

Программа make

Если запустить
make
то программа попытается найти файл с именем по умолчание Makefile в текущем каталоге и выполнить инструкции из него. Если в текущем каталоге есть несколько мейкфайлов, то можно указать на нужный вот таким образом:
make -f MyMakefile
Есть еще множество других параметров, нам пока не нужных. О них можно узнать в ман-странице.

Процесс сборки

Компилятор берет файлы с исходным кодом и получает из них объектные файлы. Затем линковщик берет объектные файлы и получает из них исполняемый файл. Сборка = компиляция + линковка.

Компиляция руками

Самый простой способ собрать программу:
g++ main.cpp hello.cpp factorial.cpp -o hello
Каждый раз набирать такое неудобно, поэтому будем автоматизировать.

Самый простой Мейкфайл

В нем должны быть такие части:

Для нашего примера мейкфайл будет выглядеть так:

Обратите внимание, что строка с командой должна начинаться с табуляции! Сохраните это под именем Makefile-1 в каталоге с проектом и запустите сборку командой make -f Makefile-1
В первом примере цель называется all . Это цель по умолчанию для мейкфайла, которая будет выполняться, если никакая другая цель не указана явно. Также у этой цели в этом примере нет никаких зависимостей, так что make сразу приступает к выполнению нужной команды. А команда в свою очередь запускает компилятор.

Использование зависимостей

Использовать несколько целей в одном мейкфайле полезно для больших проектов. Это связано с тем, что при изменении одного файла не понадобится пересобирать весь проект, а можно будет обойтись пересборкой только измененной части. Пример:

Это надо сохранить под именем Makefile-2 все в том же каталоге

Теперь у цели all есть только зависимость, но нет команды. В этом случае make при вызове последовательно выполнит все указанные в файле зависимости этой цели.
Еще добавилась новая цель clean . Она традиционно используется для быстрой очистки всех результатов сборки проекта. Очистка запускается так: make -f Makefile-2 clean

Читайте также:  Как камеру ps3 windows
Использование переменных и комментариев

Переменные широко используются в мейкфайлах. Например, это удобный способ учесть возможность того, что проект будут собирать другим компилятором или с другими опциями.

Это Makefile-3
Переменные — очень удобная штука. Для их использования надо просто присвоить им значение до момента их использования. После этого можно подставлять их значение в нужное место вот таким способом: $(VAR)

Что делать дальше

После этого краткого инструктажа уже можно пробовать создавать простые мейкфайлы самостоятельно. Дальше надо читать серьезные учебники и руководства. Как финальный аккорд можно попробовать самостоятельно разобрать и осознать такой универсальный мейкфайл, который можно в два касания адаптировать под практически любой проект:

Источник

How do I make this file.sh executable via double click?

First off I’m using Mac.

Next, I need to execute this «file.sh» we will call it. Everytime I need to execute it I have to open Terminal and type:

This is okay, but I feel like it would be a lot quicker if I make the file execute on double click, don’t you think?

So my question is, how do I make this file executable via double click?

My ideas were either:

a) type something like chmod into terminal and change permissions?

b) make a file, put code I wrote above in it ^ and then make that file executable?

c) make an automation somehow to do this?

Which way is best, or is there an even better way? Also please explain as much as you can, I’m new to Terminal. Thanks.

5 Answers 5

By default, *.sh files are opened in a text editor (Xcode or TextEdit). To create a shell script that will execute in Terminal when you open it, name it with the “command” extension, e.g., file.command . By default, these are sent to Terminal, which will execute the file as a shell script.

You will also need to ensure the file is executable, e.g.:

Without this, Terminal will refuse to execute it.

Note that the script does not have to begin with a #! prefix in this specific scenario, because Terminal specifically arranges to execute it with your default shell. (Of course, you can add a #! line if you want to customize which shell is used or if you want to ensure that you can execute it from the command line while using a different shell.)

Also note that Terminal executes the shell script without changing the working directory. You’ll need to begin your script with a cd command if you actually need it to run with a particular working directory.

Источник

How to compile a C program with make on Mac OS X Terminal

I recently bought a Macbook Pro and I want to do some coding in C with the terminal.

I’m able to compile the code with this command:

But I want to compile it with the make command because I know it is best practice and I want to follow best practice.

Читайте также:  Driver epson perfection 1260 windows

This command is giving me the following output:

Note that I have installed Xcode and Xcode developer command line tools and in the folder /usr/bin I see the make and makefile properties.

Does anyone have any hint on what should I do to be able to compile with makefile and cc argument?

3 Answers 3

Create a file called Makefile on the same path with this content:

Of course, replace appname with the name of your program

Note: There must be a «tab» (not spaces) before

I was following the same tutorial, and ran into a similar problem.

I don’t know what exactly you did, but I think the mistake was running the wrong command. You typed make filename cc filename.c -o filename , but the tutorial instructed us to use make filename , without the cc filename.c -o filename part. Maybe you read an old version?

And, make filename works fine, You don’t need a Makefile.

FYI, Here’s how I ran into the problem and how I solved it:

typed the code below, and saved it in a file named «ex1»

  • typed make ex1 in terminal
  • got error message make: Nothing to be done for ‘ex1’.
  • As you can see, my mistake was that the file name of the source code should be ex1.c, NOT ex1.

    And as I change the file name to ex1.c, and executed make ex1 , it worked.

    Источник

    Question: Q: How do I make a .sh file unix executable?

    I have a .sh file that is showing type as a plain text file. I need to make it a Unix Executable file. When I try to do this in Terminal with a chmod command it doesn’t change.

    There’s other odd behaviour. If I make a duplicate of the file (‘xxxx.sh copy’) it says it’s a Unix executable file. If I delete the ‘copy’ bit, it’s back to a plain text file. If I leave a space after sh, it stays executable. But I’m not convinced it is.

    Can anyone help?

    iMac 24-inch, Mac OS X (10.5.5)

    Posted on Dec 9, 2008 4:29 AM

    All replies

    Loading page content

    Page content loaded

    in the shell type the following;

    ls -la /Users/rodney/bin/scan-net
    -rwxr—r— 1 rodney staff 50 Jul 19 2007 /Users/rodney/bin/scan-net

    in this case you would want to make the file in question eXecutable, by doing;

    chmod 744 /Users/rodney/bin/scan-net

    to get the eXecutable bit set.

    Dec 9, 2008 7:20 AM

    specifically what command are you running?

    Try *sudo chmod +x path/to/file*

    Dec 9, 2008 7:31 AM

    when I do what you suggest. I think the xs mean it is executable, don’t they?

    Dec 9, 2008 8:56 AM

    Dec 9, 2008 9:05 AM

    when I do what you suggest. I think the xs mean it is executable, don’t they?

    You are aware that unless the script is in the path, you need to precede it with a ./
    if the script is basharooni.sh
    to run it if it is not in the path you need to enter
    ./basharooni.sh

    It’s also good, if you have not already done it, to include a shebang in the file as the first line thus:
    #!/bin/bash
    code here

    not necessary, but good scripting practice.

    Читайте также:  Linux on dex s10

    Dec 9, 2008 9:14 AM

    Dec 9, 2008 9:36 AM

    Dec 9, 2008 10:01 AM

    Are you trying to create a double-clickable file?

    Or do you just want to execute it from a Terminal command line?

    From what you have been saying, it sounds like the .sh has an *Open With. * association to a program such as TextEdit, or similar text editor.

    As others have said, from the Terminal command line prompt you can run the script by typing something like ./yourscriptname.sh

    But if you want to double-click on the file from the Finder, then you would do better to remove the .sh type field altogether, or giving it a type of .command

    Then again, double-clicking on shell scripts does not always yield the results expected 🙂

    Источник

    Is there any way to make a dual executable file for Mac/Windows?

    I’m looking for a way to make a dual executable file for Windows/Mac. That is, I can execute the file in either OS and it would run some piece of code that I want for that OS. This code can be either a script or (preferably) natively compiled code, but it needs to run on the vanilla OS without needing any extra tools or libraries installed. The other requirement is it needs to be a single file.

    Anyone know of a way to do this or is this even possible?

    8 Answers 8

    The only way I can see this working is having extra tools installed:

    • Scripts: The command parsers are extremely different between the Mac (bash shell) and Windows (which has 2: PowerShell and the original, don’t know its technical name). You’d either have to have Services for Unix/Cygwin/Insert-other-UNIXy-Environment here installed on the Windows box, or use something like perl or another scripting language. In either event, at least the Windows box, and possibly the Mac, need additional out-of-box tools.
    • Executables: The only way you can pull this off is to use Java, .NET/Mono or some other cross-platform bytecode-based virtual machine environment. Hence, you are still dependent on tools which are not in-box. (IIRC, Java doesn’t ship with Windows, and Mono doesn’t ship with Mac.)
    • Other Issues: The biggest issue you’ll run into after dealing with the tool dependency is that paths are identified differently on both systems. Understanding that Mac paths are generally Unix-style paths (although I believe «old-school» Mac colon-separated paths are still valid). You’ll also have to deal with different file locations and default locations based on both environments. This will be a pain.

    Now, if you can get away with using a cross-compile instead of binary compatibility, you may have an answer in a tool called RealBasic. It was originally Mac-based, but there are versions for Windows and Linux as well. I used to play around with it in the early part of this decade, and it was pretty neat, but not something I ever used professionally. This will, if you’re careful, allow you to write the code once, and compile the very same code as native Mac, Linux and Windows applications.

    Источник

    Оцените статью