Xcode command line tool - how to run in terminal? - xcode

When you create a Command Line Tool project in Xcode you get this, in main.m:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
// insert code here...
NSLog(#"Hello, World!");
}
return 0;
}
I can run this from Xcode. But I want to compile it so that I can run it from Terminal. What are the steps?

Assuming your executable is named "my_program", and it's in the "/foo/bar/Debug" directory:
cd /foo/bar
./my_program
If you aren't sure how to find the program file itself, you can right-click it (i.e.: the "product") and "Show in Finder" as shown in this screenshot:

You can have the terminal launch everytime you run the application through editing the scheme. I believe this became available from Xcode 8.0.
Access Edit Scheme
Switch Console from Use Xcode to Use Terminal

In Xcode 9 you can try the following (works for me in June 2018):
instead of 'edit scheme' click 'new scheme', give it a name and save
now choose that new scheme you've just created and click 'edit
scheme'
go to the 'Info' tab and in a menu 'Executable' choose
'Other...'
in file window go to search input field and type
'terminal' and click on its icon when you find it. Now you should see 'Terminal.app' in 'Executable' field
go to the 'Arguments' tab, click on + and copy and paste this line there: ${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}
click 'close' and run your program with your new scheme selected
Normally Xcode will open terminal for you. If not, you may also turn off any debug related fields in the 'Info' tab. Hope this helps!
Full tutorial here:
https://www.raywenderlich.com/163134/command-line-programs-macos-tutorial-2

Related

Execute gofmt on file save in IntelliJ

I use IntelliJ with the Golang plugin. Is it possible to configure the IDE to execute gofmt on file save?
Of course you can.
install File Watchers plugin
open "Preferences->Tools->File Watchers" & Add a new watcher
set File Type: Go, Program: the abosolute path of gofmt, Arguments: -w $FilePath$
click OK
Gogland EAP 16 deprecated the On Save actions and replaced them with the File Watchers plugin.
If you have previously configured On Save actions, the IDE will prompt you to install the plugin and configure everything automatically. If you want to set it up from scratch yourself, check if you have File Watchers plugin and if not install it.
Enable gofmt:
Go to Settings | Tools | File Watchers.
Click the + button and select go fmt.
The default values are good.
In Advance Options select:
Auto-save edited files to trigger the watcher
Trigger the watcher on external changes
Click ok!
You can do the same for goimports and gometalinter.
If you are using Gogland, you have an option On Save under Preferences
Updated:
For new versions of the Goland:
open File->Settings->Tools->File Watchers
click on + button and choose go fmt
press Ok
Done :)
September 2021 Update.
If you are using GoLand with the 2021.2 version and higher (July 2021), there are a few options to enable gofmt on save besides File Watchers.
Enable Run gofmt on code reformat under Preferences/Settings | Editor | Code Style | Go | Other.
Enable Reformat code under Preferences/Settings | Tools | Actions on Save.
Press Command + S on macOS or Ctrl + S on Windows/Linux to save your changes.

Sublime Text: "MarGo: Missing required environment variables: GOPATH"

In order to program with Golang in a more productive way, I just installed GoSublime for Sublime Text 2, as explained on their official GitHub repository:
Installation
Sublime Package Control allows you to easily install or remove
GoSublime (and many other ST2 packages) from within the editor. It
offers automatically updating packages as well so you no longer need
to keep track of changes in GoSublime.
Install Sublime Package Control (if you haven't done so already) from
http://wbond.net/sublime_packages/package_control .
Be sure to restart
ST2 to complete the installation.
Bring up the command palette (default ctrl+shift+p or cmd+shift+p) and
start typing Package Control: Install Package then press return or
click on that option to activate it. You will be presented with a new
Quick Panel with the list of available packages. Type GoSublime and
press return or on its entry to install GoSublime. If there is no
entry for GoSublime, you most likely already have it installed.
Now, whenever I launch Sublime Text, I have the following error message:
MarGo: Missing required environment variables: GOPATH
See the `Quirks` section of USAGE.md for info
And a usage.md file opens automatically, with the following content:
Usage
=====
Note
----
* Unless otherwise mentioned, `super` replaces `ctrl` in key bindings on OS X.
* A mention of a (GO)PATH variable uses a colon(`:`) as the separator.
This is the PATH separator on Linux and OS X, Windows uses a semi-colon(`;`)
Settings
--------
You may customize GoSublime's behaviour by (creating and) customizing the file `Packages/User/GoSublime.sublime-settings`. Default settings are documented in `Packages/GoSublime/GoSublime.sublime-settings`. **WARNING** Do not edit any package file outside of `Packages/User/`, including files inside `Packages/GoSublime/` unless you have a reason to. These files are subject to being overwritten on update of the respective package and/or Sublime Text itself. You may also inadvertently prevent the respective package from being able to update via git etc.
Quirks
------
This section assumes you know what `GOPATH` is and how to set it. If you don't, please see http://golang.org/doc/code.html
In some systems, environment variables are not passed around as expected.
The result of which is that some commands e.g `go build` don't work
as the command cannot be found or `GOPATH` is not set. To get around this
the simplest thing to do is to set these variables in the settings file.
See the documentation for the `env` and/or `shell` setting, both documented in the default
settings file `Packages/User/GoSublime.sublime-settings`
Code Completion
---------------
Completion can be accessed by typing the (default) key combination `CTRL+[SPACE]` inside a Golang file.
Key Bindings
------------
By default, a number of key bindings are provided. They can be viewed by opening the command palette
and typing `GoSublime:` or via the key binding `ctrl+dot`,`ctrl+dot` (or `super+dot`,`super+dot` on OS X).
Wherever I refer to a key binding with `ctrl+` it is by default defined as `super+` on OS X unless stated otherwise.
Useful Key Bindings
-------------------
Often when commenting out a line, the immediate action following this is to move the cursor to the next line either to continue working or comment out the following line.
With this key binding, you can have the line commented out and the cursor automatically moved to the next line.
{ "keys": ["ctrl+/"], "command": "gs_comment_forward", "context": [{ "key": "selector", "operator": "equal", "operand": "source.go" }] },
Package Imports
---------------
Pressing `ctrl+dot`,`ctrl+p` will open the package list from which you can quickly import or delete a package import.
The usage is the same for both operations. If the package is already imported then it will appear near the top
and be marked as a *delete* operation, so in effect it is a toggle. If you want to edit the alias of a package e.g
a database driver: first import the package as normal and then press `ctrl+dot`,`ctrl+i` to quickly jump
the last imported package. Once edited you can return to where you were by pressing `ctrl+dot`,`ctrl+[`
Building, Testing and the Go command
------------------------------------
GoSublime comes with partial command/shell integration `9o`. For more information about 9o, see Packages/GoSublime/9o.md
or from within Sublime Text press `ctrl+9` or `super+9` and type `help`.
To run package tests you have 3 options.
* press `ctrl+dot`,`ctrl+t` to open the testing quick panel. This offers basic/common options such
as running all benchmark functions or running a single test function.
* inside a `_test.go` file, press `ctrl+shift` and left-click on the name of a Test, Benchmark or Example
function e.g. `TestAbc` to execute that function only.
* if the above options are too minimalistic or you would otherwise like to call `go test` with your own options,
open 9o by pressing `ctrl+9` where you have access to the `go` command.
In the case of building a package, 9o provides a replay command (see 9o.md for details) that will execute
the command if the pkg is a command pkg (package main) or run all tests if it's a normal pkg.
The replay command is bound to `ctrl+dot`,`ctrl+r` for easy access.
GoSublime provides an override for the Sublime Text build-system via `ctrl+b`. In the menu `Tools > Build System` it's named `GoSublime`.
`ctrl+b` is automatically handled by Sublime Text, so if you have another `Go` build system chosen, `ctrl+b`
will execute that instead. To access the `GoSublime` build system directly press `ctrl+dot`,`ctrl+b`.
This build system simply opens 9o and expand the last command. i.e. executes the 9o command `^1`.
Per-project Settings & Project-based GOPATH
-------------------------------------------
If you have a settings object called `GoSublime` in your project settings its values will override those
inside the `GoSublime.sublime-settings` file. As a side-effect you may set a specific GOPATH for a single
project.
`my-project.sublime-project`
{
"settings": {
"GoSublime": {
"env": {
"GOPATH": "$HOME/my-project"
}
}
},
"folders": []
}
If the only setting you use this functionality to change is the GOPATH, then you may be able to find
success by adding the string `$GS_GOPATH` to your global `GOPATH` setting e.g.
{
"env": { "GOPATH": "$HOME/go:$GS_GOPATH" }
}
`GS_GOPATH` is a pseudo-environment-variable. It's changed to match a possible GOPATH based on:
* the current working directory, e.g. `~/go/src/pkg` then `$GS_GOPATH` will be `~/go/`
* or the path the current `.go` file (or last activated `.go` file if the current file is not `.go`) e.g. if your file path is `/tmp/go/src/hello/main.go` then it will be `/tmp/go`
If you would like to use `GS_GOPATH` exclusively, you may set the option `use_gs_gopath` to true.
This automatically changes `GOPATH` to the value of `$GS_GOPATH` if `$GS_GOPATH` is not empty.
This allows you to e.g. automatically adapt `GOPATH` to your current project rather than
reverting to your normal `GOPATH`.
Lint/Syntax Check
-----------------
The source is continuously scanned for syntax errors. GoSublime will try to catch some common errors, like
forgetting to call flag.Parse (if this causes false positives, please file a bug report).
Apart from the highlighting in the view using a dot icon in the gutter and usually underlining the
first character of an error region. You are given an entry in the status bar in the form: `GsLint (N)`
where `N` is the number of errors found in that file. You can show the list of errors and navigate to
them by pressing `ctrl+dot`,`ctrl+e`. Errors for the current line are shown in the status bar.
Fmt
---
By default `ctrl+s` and `ctrl+shift+s` are overridden to fmt the the file before saving it. You may also
fmt a file without saving it by pressing `ctrl+dot`,`ctrl+f`
Godoc/Goto Definition
---------------------
To show the source and associated comments(documentation) of a variable press `ctrl+dot`,`ctrl+h` or
using the mouse `ctrl+shift+right-click`. This will show an output panel that presents the full
definition of the variable or function under the (first) cursor along with its comments.
To goto the definition instead, press `ctrl+dot`,`ctrl+g` or alternatively using the mouse `ctrl+shift+left-click`.
Declarations/Code Outline?
--------------------------
A very minimal form of code outline is provided. You can press `ctrl+dot`,`ctrl+d` to list all the declarations
in the current file.
New File
--------
Pressing `ctrl+dot`,`ctrl+n` will create a new Go file with the package declaration filled out.
It will try to be intelligent about it, so if the current directory contains package `mypkg` it will use that as the package name.
Misc. Helper Commands
---------------------
The following commands can be assigned key bindings to further improve your editing experience.
* gs_fmt - this command runs `gofmt` on the current buffer. Also available via the key binding `ctrl+dot`,`ctrl+f`.
* gs_fmt_save, gs_fmt_prompt_save_as - these commands will run the `go_fmt` followed by `save` or `prompt_save_as` - these are bound to `ctrl+s` and `ctrl+shift+s` respectively, by default.
* gs_comment_forward - this command will activate the `ctrl+/` commenting and move the cursor to the next line, allowing you to comment/uncomment multiple lines in sequence without breaking to move the cursor. You can replace the default behaviour by overriding it in your user key bindings (Preferences > Key Bindings - User) with `{ "keys": ["ctrl+/"], "command": "gs_comment_forward", "context": [{ "key": "selector", "operator": "equal", "operand": "source.go" }] }`
Some people seem to have had the same issue:
Idiotproof instructions for MarGo: Missing required environment variables: GOPATH #310
How come USAGE.MD opens everytime I open Sublime? #601
gopath is set, but still show "MarGo: Missing required environment variables: GOPATH" #520
And the root cause of the problem could be that the GOPATH has not been defined.
Mine has been — export GOPATH=$HOME/code/go — and I am able to run Go (and .go files) on my computer.
Any idea of how this can be fixed?
You need to set gopath in the GoSublime settings.
Go to:
Preferences -> Package Settings -> GoSublime -> Settings – User
And paste that code there:
{
"env": {
"GOPATH": "$HOME/code/go"
}
}

Fix Quick Look for TypeScript files

My Mac recognises the .ts extension as MPEG-2 Transport Stream, while I use it more often as TypeScript files. Because of that Quick Look does not show the contents of .ts files.
I found on Stackoverflow that I should be able to assign custom extensions to the text editor, but I'm not sure how.
QLColorCode is a very nice Quick Look plugin which allows you to set syntax highlighting for ANY extension file you want.
1. Install QLColorCode Quick Look plugin
If you have Homebrew, you can install it with:
brew cask install qlcolorcode
Otherwise, you can just copy / paste the QLColorCode.qlgenerator to your ~/Library/QuickLook/ folder from a release.
2. Add .ts and .tsx syntax highlighting support
First get the kMDItemContentType of the extension you want to quick look at with the plugin:
mdls -name kMDItemContentType /path/to/any/file.ts
Add an entry with the string returned by the previous command to the plugin settings list — for a .ts file, this should be public.mpeg-2-transport-stream. To do so, just open the file ~/Library/QuickLook/QLColorCode.qlgenerator/Contents/Info.plist with any text editor (it's not a compiled file) and in the section CFBundleDocumentTypes > Item 0 > LSItemContentTypes (~ 15th line), add a line like this:
<string>public.mpeg-2-transport-stream</string>
You can find more information on how to add language type support to the plugin in the project README.md.
Here is the original post where I found all this useful information.
According this article, there is another solution:
1) Remove filetype definition from: /System/Library/CoreServices/CoreTypes.bundle/Contents/Info.plist
You need to do that in recovery mode.
215 => {
"UTTypeConformsTo" => "public.movie"
"UTTypeDescription" => "MPEG-2 Transport Stream"
"UTTypeIdentifier" => "public.mpeg-2-transport-stream"
"UTTypeTagSpecification" => {
"public.filename-extension" => [
0 => "ts"
]
}
}
2) Then run
/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister -kill
I managed to get QuickLook to display .ts files as plain text.
The necessary step was to remove Movie.qlgenerator from the directory /System/Library/QuickLook.
The downside is, that QuickLook can't preview any types of movies any more...
Update 2016-04-12:
In OSX El Capitan it seems not possible to simply remove a file from /System/Library/QuickLook (probably because of System Integrity Protection).
I managed to remove the Movie.qlgenerator with the following steps:
Back up the file first
Boot into Recovery Mode: Restart and press-and-hold Cmd-R
Open a terminal
disable SIP: csrutil disable
cd /Volumes/Macintosh HD/System/Library/QuickLook (your volume name may be different)
rm -rf Movie.qlgenerator
csrutil enable
csrutil status -> Verify SIP is turned on again
Restart
After the above steps I could quick-look my .ts files.
The best part: I put the Movie.qlgenerator I had backed up in the first step into ~/Library/QuickLook and now I have also quick-look previews for movies ...

import tuneup.js file not found

Using the Xcode iOS Instruments UI Automation tuneup.js javascript library https://github.com/alexvollmer/tuneup_js .
I'm having challenges understanding the current working diretory of my launched instrument.
I have not been able to make a relative path to the tuneup/tuneup.js script. The destination of the relative path is of course "tuneup/tuneup.js". But what is the starting point?
Here's the code:
// This works:
#import "/Users/mikes/Documents/Full/Path/To/File/Tests/tuneup/tuneup.js"
// These do not work:
//#import "tuneup/tuneup.js"
//#import "Tests/tuneup/tuneup.js"
//
// See https://github.com/alexvollmer/tuneup_js
//
test("First Screen", function(target, app) {
var window = app.mainWindow();
window.logElementTree();
});
See tuneup.js reports "Can't find variable" for test() method for a related question.
-Thanks
-Mike
I'm willing to bet that the reason this isn't working is because you created an embedded script in the Instruments document. Instead of choosing "Add > Create Script" in the sidebar of instruments, you need to choose "Add > Import" and import your script file from the file system. That will link the Instruments document to your script file and when you use the #import keyword, it will look in the directory relative to where your script file resides.
Embedded (as opposed to imported) scripts do not have a "current directory" which is why you need to absolute path to the tuneup.js file.

Open CV, image loading issue on Mac OS X

I think my question is pretty basic. I was trying to get Open CV to install on my OSX Lion. I had followed all the steps recommended on this link http://tilomitra.com/opencv-on-mac-osx/
However, when I run the C++ code recommended on the website in Xcode, it fails to load an image with the cvLoadImage( ) function. I have placed my image in the project folder (as recommended). Here is the code I was running:
// Example showing how to read and write images
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv/cvaux.hpp>
int main(int argc, char** argv)
{
IplImage * pInpImg = 0;
// Load an image from file - change this based on your image name
pInpImg = cvLoadImage("my_image.jpg", CV_LOAD_IMAGE_UNCHANGED);
if(!pInpImg)
{
fprintf(stderr, "failed to load input image\n");
return -1;
}
// Write the image to a file with a different name,
// using a different image format -- .png instead of .jpg
if( !cvSaveImage("my_image_copy.png", pInpImg) )
{
fprintf(stderr, "failed to write image file\n");
}
// Remember to free image memory after using it!
cvReleaseImage(&pInpImg);
return 0;
}
So during execution, the code builds successfully, but always ends up in the following loop and halts execution:
if(!pInpImg)
{
fprintf(stderr, "failed to load input image\n");
return -1;
}
Has anyone faced such a problem before? How could I solve this?
(During installation of 'Macports' and 'Cmake', I had received an alert saying that Xcode was not installed or was installed without 'Command Line Tools'. But as per another thread on this forum, I had installed these from the Xcode-->Preferences-->Downloads folder on installing Xcode.
However, still during installation, 'Macports' and 'Cmake' gave me warnings, but installed anyway. But could this be the issue? )
Thank you!
The problem is that you're putting the image into the project folder instead of the folder containing your executable. You can either put the image file in the folder with the executable or put the full path to the image in the call to cvLoadImage.
Older versions of Xcode put the executable in either the build/Debug or build/Release folder in the project folder. Newer versions of Xcode put the build products in the project folder in the DerivedData folder. You can find the DerivedData folder by going to File -> Project Settings… and clicking the arrow next to the folder path:
In the project folders, go to 'Products' > right click on the executable file > 'Show in Finder' > put the input image there. The output image ('.png' file) will go here as well.

Resources