Как программировать на objective с на windows

Quick Start Tutorial

Overview

The Quick Start provides you with a hands-on introduction to the Windows Bridge for iOS. It covers the layout of the SDK, shows you how to import the code from a simple Xcode project into Visual Studio, and demonstrates how to call Windows APIs using Objective-C.

Objectives

In this Quick Start, you will learn how to:

  • Enable Objective-C syntax highlighting for Visual Studio by installing a Visual Studio extension
  • Import an existing Xcode project into Visual Studio
  • Build the imported project as a Universal Windows Platform (UWP) app and run it on Windows
  • Customize the imported project to call Windows APIs from Objective-C

Tools you’ll use

  • A computer or virtual machine running Windows 10, build 10586 or higher. (Validate your version number here).
  • Visual Studio 2015 Update 3. Visual Studio 2015 Community is available for free here. Select (at least) the following components during installation:
    • Programming Languages -> Visual C++
    • Universal Windows App Development Tools (all)
  • The latest release of the Windows Bridge for iOS SDK, which you can download here.

If you’re not using a pre-configured VM and need to install the tools, check the «Using the Bridge» section of the Windows Bridge for iOS website for the installation instructions.

The Challenge

Sub-challenge 1: Building and running Objective-C on Windows

Are you ready to get started? This section walks you through the basics of developing with the Windows Bridge for iOS. First, it shows you how to enable Objective-C syntax highlighting for Visual Studio so that you can have a great development experience. Next, it shows you how to use the vsimporter tool to import an Xcode project into Visual Studio, build the project for Windows, and run the resulting UWP app.

  1. The files required to enable Objective-C syntax highlighting in Visual Studio are provided with the SDK, but need to be manually installed. To locate the files:
    • Double-click the WinObjC shortcut (1) on the Desktop. If you downloaded the SDK, just go to your download location and unzip the file.
    • Navigate to the bin directory and double-click the objc-syntax-highlighting.vsix (2) file to begin installing the Visual Studio extension.

  1. When the installation wizard window launches, click Install (1).

 
3. After the extension installation is complete, you’ll see a confirmation dialog. Click Close (1).

  1. Now that syntax highlighting is enabled, it’s time to import your first Xcode project using the command line vsimporter tool.
    • Open a command line window by clicking the Start (1) button.
    • Type cmd (2) in the search box and press Enter.

  1. In the command line window, navigate to the directory of the project. For this challenge, you’ll use the WOCCatalog Xcode project, so type the command cd C:\winobjc\samples\WOCCatalog (1) and press Enter (if you downloaded the SDK to another location, adjust the command path accordingly).

  1. Since the SDK is provided with the sample Xcode projects and their equivalent Visual Studio solutions are already created, we’ll delete and re-generate them. Navigate there using the file explorer, or double-click the WinObjC (1) shortcut on the Desktop and navigate to the samples\WOCCatalog directory.

  1. Notice that the WOCCatalog folder contains the Xcode project WOCCatalog.xcodeproj (1), the Visual Studio solution (2) for that project created by the vsimporter tool, and a folder that contains headers (3) necessary for the Visual Studio solutions.

* Delete the **Visual Studio solution** (1) and the **folder that contains the headers** (2), so that you can re-generate them with the **vsimporter** tool and get familiar with the Xcode project import process. 

* After you’re done, your directory should just contain the Xcode project files and included tests.

  1. Now that the project directory is ready, go to the previously opened command line window, type the command ..\..\bin\vsimporter.exe (1), and press Enter. This command runs the vsimporter tool, which creates a Visual Studio solution for the Xcode project.

  1. If you look back at the file explorer, you’ll notice that the WOCCatalog-Winstore10.sln (1) file, which corresponds to the Visual Studio solution, was recreated. Similarly, the folder that contains the necessary header (2) files was also recreated. Open the imported project in Visual Studio by double-clicking the solution file (1).

  1. Now that the project is open in Visual Studio, it’s time to build and run it. Begin by setting the appropriate startup project.
    • In Solution Explorer (1), under Solution WOCCatalog-WinStore10\WOCCatalog, right-click the project WOCCatalog (2). When the context menu comes up, select Set as StartUp Project (3). 

  1. Now that the startup project is specified, just press Ctrl+F5 to build and run the application without debugging. If a confirmation window pops up, click Yes (1).

  1. After Visual Studio finishes building the sample app, it will launch in a new window. Take some time to play around with the app and explore the associated source code.

  1. Now that you’ve explored the app, let’s take a look at its code flow through some basic run-time debugging. Begin by configuring Visual Studio according to the Setup Required section of the debugging wiki page.

  2. Once the debugging setup is complete, open a source file in Visual Studio by double-clicking MainViewController.m (1) in the Solution Explorer window, under **WOCCatalog\WOCCatalog (Universal Windows)\WOCCatalog**. Notice that the Objective-C code has syntax highlighting, which the objc-syntax-highlighting.vsix you previously installed enabled.

  1. Now that the source file is open, set a break point by clicking on the left sidebar (1) of the source window on the line that you want the execution of the application to pause. Once that’s done, re-run the application with debugging by pressing F5. A good place to set the breakpoint is in the viewDidLoad method, which is executed as soon as the main menu of the app loads.

  1. After the app launches, execution pauses and you can explore the value of variables in the Locals debugger window (1). When you’re ready to resume execution, click Continue (2) or, if you’d like to continue debugging, use the Step Into (3), Step Over (4) and Step Out (5) options. Keep exploring the source files and setting breakpoints to get familiar with the sample application.

That’s it! You now have a UWP app written in Objective-C running on Windows and built using Visual Studio. After you’re done exploring the application, continue with the next sub-challenge!

Sub-challenge 2: Using Windows APIs and XAML Controls from Objective-C

Now that you know the basic development flow to bring your existing code to another platform, let’s explore the possibilities of Objective-C development on Windows. In this section, you will learn how the Windows Bridge for iOS allows you to extend your app by adding XAML controls to a UIKit-based application.

  1. Begin by locating and opening the file XamlViewController.m (1) in the Solution Explorer window. Similar to before, you can find it under Solution WOCCatalog-WinStore10\WOCCatalog\WOCCatalog (Universal Windows)\WOCCatalog.

  1. This file is the controller for the XamlControls view of the app. Run the app (Ctrl+F5) and open that view by clicking the XamlControls (1) item.

  1. Now, in the XamlViewController.m file in Visual Studio, scroll down to locate the cellForRowAtIndexPath (1) method. Take a moment to understand this function and note that essentially it’s creating XAML controls in Objective-C, wrapping them into CALayers, placing those CALayers into UIViews, and then adding the Views to cells in a table.

 
4. Next, you’ll see that the bottom of the XamlControls view has a slider control (1). Locate it in the application and the associated code in the XamlViewController.m file.

  1. As you look at the code, you’ll notice that currently, the slider control does not specify a callback function. Being able to leverage XAML events through Objective-C is a common scenario, so let’s explore it by adding an event to the slider so that a callback occurs whenever the user changes the value of the slider. For reference, the Slider class is documented on MSDN and the specific event of interest is the ValueChanged event. Insert the following code after the slider control is instantiated (1) to add a simple callback. The construct of this code will be explained shortly.

     [slider addValueChangedEvent:^ (RTObject * sender, WUXCPRangeBaseValueChangedEventArgs * e) {
     		NSLog(@"Value Changed Event");
     } ];
    

  1. This simple callback prints the message Value Changed Event in the console. To make sure that it works, build and run the app, go to the XAMLControls view, and move the slider. The message should be displayed (1) on the debugging output window (2), which you can quickly access by pressing Ctrl+Alt+o.

 
7. As before, you can also set a breakpoint on the instruction that prints the message (1) and the execution of the app will pause for debugging when the slider is moved. To start the app with debugging enabled, press F5 in Visual Studio.

 
8. Next, to get a sense of the general structure of the Objective-C bindings and better understand how XAML interactions work, take a look at the header files in C:\winobjc\include\Platform\Universal Windows\UWP. For the slider, since it is a Windows.UI.Xaml.Controls class (as you can see by reading MSDN), you should look at the C:\winobjc\include\Platform\Universal Windows\UWP\WindowsUIXamlControls.h (1) header file. Open the header file in Visual Studio by double clicking it.

  1. If a pop-up window that reads “How do you want to open this file?” appears, select Visual Studio (1) and click OK (2).

  1. Previously, you added a callback for the ValueChanged event of the slider, which is inherited from the Windows.UI.Xaml.Controls.Primitives.RangeBase class (again, see MSDN). Locate (1) the corresponding binding on the header file (you can use the search function by pressing Ctrl+F5, entering the class you want to search for, and pressing Enter).

  1. Looking back at the XamlViewController.m file, you can see the addValueChangedEvent method (1) that corresponds to the first part of the callback message of the slider (2). You can also see that it takes a WUXPCRangeBaseValueChangedEventHandler parameter (3).

  1. In the WindowsUIXamlControls.h file, locate the binding for WUXCPRangeBaseValueChangedEventHandler (1). It corresponds to the Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventHandler class, which is the class of the ValueChanged event of the slider in the XamlViewController.m file (see MSDN). You can see the code block (2) that corresponds to the WUXCPRangeBaseValueChangedEventHandler parameter of the addValueChangedEvent method, which explains the second part of the callback message of the slider (3).

  1. To use other Windows APIs from Objective-C, you can use the WOCCatalog sample code as an example and/or search the Microsoft documentation for the desired API, and then locate the corresponding bindings on the header files of C:\winobjc\include\Platform\Universal Windows\UWP, as you did in the previous steps.

Now you’ve learned how to leverage XAML controls from Objective-C and add your own callback. You have also learned that to support Windows APIs, the directory include\Platform\Universal Windows\UWP of the SDK contains a set of header files, each mapping to a Windows namespace. If you’re feeling adventurous, try out the next sub-challenge where you will make the callback to do something more useful.

Sub-challenge 3: Make the slider adjust the video’s volume

Now that you’re comfortable extending the app, this section will focus on making the slider event callback function more useful. Rather than just output a debugging message, you will modify the callback function to adjust the volume of a playing video.

  1. If you run the sample app again and navigate to the XamlControls view, you’ll notice that there’s a XAML video player (1).

  1. In the source code for this view in the XamlViewController.m file, locate where the mediaElement (1) control that corresponds to the video is created and placed.

  1. The mediaElement class documentation is available on MSDN. As you review the documentation, you’ll find that to modify the volume of the media player, you need to set a property called volume with a value between 0 and 1. The following code illustrates how to set the volume, where newVolume should correspond to the value of the slider:

     self.mediaElement.volume = newVolume;
    
  2. To get the current value of the slider in the callback, you can use the e.newValue property in the event args, as explained by the RangeBaseValueChangedEventArgs class documentation on MSDN. Note that the slider value will be between 0 and 100; the minimum and maximum values of the slider set on its instantiation (1). That means that some minor conversion will be necessary since the volume control is expecting a value between 0 and 1.

  1. Given the information in Steps 3 and 4, it is straight forward to determine that the slider callback code should be the following:

     [slider addValueChangedEvent:^ (RTObject * sender, WUXCPRangeBaseValueChangedEventArgs * e) {
     		NSLog(@"Value Changed Event");
     		self.mediaElement.volume = e.newValue/100;
     } ];
    
  2. Add the code to the slider callback (1), build and run the application, and move the slider on the XamlControls view. The volume of the video should now be adjustable.

That’s it! Now that you’ve gotten a sense of how to use Windows APIs and XAML controls from Objective-C, feel free to play around with the rest of the app. Try adding some of your own iOS/UIKit controls to see what works and what isn’t yet supported, or try using other Windows APIs from Objective-C.

Summary

In this challenge, you learned how to import an Xcode project into Visual Studio, how to build and run that project on Windows, and how to use XAML controls and Windows APIs from Objective-C. You should now be ready to explore the possibilities of the Windows Bridge for iOS.

Next Steps

If you haven’t done so already, check the Windows Bridge for IOS website for more information and the latest news about the project.

To download the latest version of the SDK, go to the Windows Bridge for IOS GitHub page. Check the wiki for more details on how to use the bridge, how to contribute to the project, our development roadmap and more samples and tutorials.

You now have all the resources to build your Windows app!

Objective C is a general purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. It was the main programming language used by Apple Inc. for the OS X and iOS operating systems, and their respective application programming interfaces (APIs): Cocoa and Cocoa Touch prior to the introduction of Swift. It is still used for OS X & iOS application development even after the introduction of Swift by Apple Inc.

It is a superset of C programming language. It extends the features of C by including features of object-oriented programming language Smalltalk. That’s why, Objective C supports object-oriented features like Encapsulation, Data Hiding, Abstraction, Inheritance & Polymorphism.

It was originally developed in the early 1980s. It was selected as the main language used by NeXT for its NeXTSTEP operating system, from which OS X and iOS are derived. Its source code “implementation” program files usually have .m filename extension, while its “header/interface” files have .h extensions.

Environment for execution of Objective C

If you are on a Mac, then you can compile and run Objective C codes in Xcode, which you can get from Mac App Store. But those on other operating systems like Windows and Ubuntu, no need to worry. You can compile and run Objective C programs by adding support of GNU Compiler Collection(GCC) or Clang. Just follow the steps given below :

For Windows users

Go to GNUstep: Windows Installer

Then go to the download section. Then download and install all the packages in the order given below :

  1. GNUstep MSYS System(Required)(Contains MSYS/MinGW System)
  2. GNUstep Core(Required)(Contains GNUstep Core)
  3. GNUstep Devel(Recommended)(Contains Developer Tools)
  4. GNUstep Cairo(Recommended)(Contains Cairo Backend)
  5. ProjectCenter(Recommended)(Contains IDE (Like Xcode, but not as complex))
  6. Gorm(Recommended)(Contains Interface Builder (Like Xcode NIB builder))

The installation process of the each of the above packages is self-explanatory. Even if you encounter any problem, feel free to ask questions through comments.

For Linux users

GNU Compiler Collection (GCC) provides compiling support for Objective C source files through GNUstep framework. It is very easy to setup Objective-C development environment on Linux distributions.

# Fedora

Open up your terminal by pressing Ctrl-Alt-F2 and type the following command :

$ su –

$ yum install gcc-objc libobjc gnustep-base-devel gnustep-gui-devel gnustep-gui-libs gnustep-back gnustep-make gnustep-filesystem gorm-devel

This command should satisfy all the dependencies.

Note :  Do not type $ in the terminal. It is just used to show that this is one terminal command.

# Ubuntu

Install the following packages from your favourite package manager :

gobjc
gnustep
gnustep-make
gnustep-common
gnustep-core-devel
gnustep-devel

OR

Open up your terminal by pressing Ctrl+Alt+T and  type the following command :

$ sudo apt-get install gobjc gnustep gnustep-make gnustep-common gnustep-core-devel gnustep-devel

Compiling & Running Objective-C Programs

Now we have to check whether we have set up Objective-C environment correctly. Open up your favourite text editor(I recommend Notepad++, Visual Studio Code or Sublime Text) and type the following code in it :

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]){

NSLog(@”Hello, World!\n”);

return 0;}

Save your file with any name (let say FILE_NAME) but with .m filename extension.

For Windows users

Open the Shell(console) provided by GNUstep. To do it, go to Start -> All Programs/All Apps(Windows 8 or later) -> GNUstep and then open Shell.  When the Shell first starts, it places you in the home directory of GNUstep, i.e.

C:\GNUstep\home\{username}

{username} is the name by which you have logged in to Windows.

Note: Replace FILE_NAME with the file name in the commands given below.

In the Shell, switch to the directory containing FILE_NAME.m and then compile the program by running the command given below :

$ gcc `gnustep-config –objc-flags` L /GNUstep/System/Library/Libraries FILE_NAME.m o FILE_NAME lgnustepbase lobjc

It produces FILE_NAME.exe executable in the current directory.

Now, run the executable file by running the command given below in the terminal :

$ ./FILE_NAME.exe

For Linux (Fedora & Ubuntu) users

Open up your terminal and first navigate to the directory where the file is saved. Then use any one of the methods given below :

Note: Replace FILE_NAME with the file name in the commands given below.

#1 Method

Enter the following command in the terminal :

$ gcc FILE_NAME.m `gnustep-config –objc-flags` -lobjc -lgnustep-base

This should produce a.out binary in the current directory.

Now, run the executable file by running the command given below in the terminal :

$ ./a.out

#2 Method (Recommended)

Run the following command in the terminal to compile FILE_NAME.m :

$ gcc FILE_NAME.m `gnustep-config –objc-flags` `gnustep-config –base-libs` -o  FILE_NAME

This should produce FILE_NAME.out binary in the current directory.

Now, run the executable file by running the command given below in the terminal :

$ ./FILE_NAME

Now you have a fully working Objective-C programming environment setup.

Sources and References

  1. Objective-C – Wikipedia

Objective-C Tutorial | How to Program in Objective C on Windows

Tutorial: Programming in Objective C on Windows

As you embark on the journey to learn Objective C, you may wonder why you’d want to program in Objective C on Windows, when the majority of developers work with Apple devices. The reasons are diverse, but some common motivators include the desire to practice on the OS you have, or to extend your possible user community. By learning Objective C on Windows, you can develop applications that will work on an iPhone, making you a part of the exclusive group of developers who don’t just use Apple devices, but write apps for them as well.

Choosing the Right Compiler

There are several options to compile Objective C on Windows, each with its own advantages and disadvantages. One popular choice is the GNU compiler, also known as GCC. Another option is Cygwin, which provides a Unix-like environment on Windows, making it easier to develop Objective C applications. MinGW is yet another alternative, offering a free and open-source development environment. Each of these options allows you to write and compile Objective C code on Windows, but keep in mind that the resulting code will not run natively on an iPhone or other Apple devices without additional work.

The Challenge of Cross-Platform Development

As you begin to write Objective C code on Windows, you may encounter the challenge of making your applications compatible with Apple’s proprietary APIs. The iPhone API, also known as Cocoa, is tightly integrated with Apple’s proprietary hardware and software. This means that simply writing Objective C code on Windows is not enough to ensure that your application will run seamlessly on an iPhone. Apple has strict control over the Objective C language, which further complicates the process of developing cross-platform applications.

Using Windows-Compatible Versions of Next-Step Libraries

One approach to developing cross-platform Objective C applications is to use Windows-compatible versions of Next-Step libraries, such as FoundationKit. These libraries allow you to write Objective C code on Windows that can run on both Windows and iOS devices. However, this approach may require additional effort and research to ensure compatibility and accuracy.

The Need for Additional Files

While it is possible to write Objective C code on Windows using Windows-compatible versions of Next-Step libraries, there may be additional files required to make your application truly cross-compatible. These files can be difficult to obtain, and may require a significant amount of research and sleuthing on your part. For example, you may need to find compatible versions of libraries or frameworks that are specifically designed for use with Windows and iOS.

The Easier Route: Developing on Apple Devices

If you’re looking for an easier and more straightforward approach to developing Objective C applications, you may want to consider using an Apple device to write and compile your code. This allows you to take full advantage of Apple’s proprietary APIs and development tools, making it easier to create applications that run seamlessly on Apple devices. While this approach may require a significant upfront investment in Apple hardware and software, it can save you time and effort in the long run.

Conclusion

Programming in Objective C on Windows can be a challenging but rewarding experience. By choosing the right compiler and using Windows-compatible versions of Next-Step libraries, you can develop applications that run on both Windows and iOS devices. However, it’s essential to be aware of the additional challenges and limitations that come with developing cross-platform applications. Whether you choose to develop on Apple devices or use Windows, the key to success lies in your ability to adapt to the unique demands of each platform. With persistence and patience, you can overcome these challenges and become a skilled Objective C developer, capable of creating innovative and engaging applications for both Windows and iOS users.

Objective-C Tutorial | How to Program in Objective C on Windows

📝 Objective-C for Windows: A Complete Guide

So, you’re interested in writing Objective-C on the Windows platform, huh? 🖥️ Well, you’re in luck! In this blog post, we’ll address common issues and provide easy solutions to help you get started. Let’s dive in! 💪

Integrating Objective-C with Visual Studio

Many developers wonder if they can somehow integrate Objective-C into Visual Studio. While Visual Studio doesn’t natively support Objective-C, you can still write Objective-C code on Windows using other tools and frameworks.

One popular approach is to use Cygwin and gcc. Cygwin is a large collection of GNU and Open Source tools that provide functionality similar to a Linux distribution on Windows. By installing Cygwin and gcc, you can compile Objective-C code and run it on Windows.

So, how can you integrate Cygwin and gcc into Visual Studio? 🤔 While there isn’t a direct integration, you can use Visual Studio as your code editor and then compile and run your Objective-C code through the Cygwin terminal. This way, you get the best of both worlds!

🚀Linking Windows SDK with Objective-C

Now, what about accessing Windows SDK functionality when writing Objective-C? 🤔 We got you covered! Although it may seem like a different beast, you can still write assembly code and link in the Windows DLLs to gain accessibility to those calls.

To link in and use the Windows SDK, you’ll need to include the necessary headers, libraries, and DLLs in your Objective-C project. You can find extensive documentation on the Windows Dev Center website, which provides detailed instructions and examples for different SDK functionalities. 💡

📚Resources to Help You on Your Objective-C Journey

Learning new things can be challenging, but fortunately, there are great resources out there! When it comes to Objective-C on Windows, we recommend the following online and book resources:

  1. Objective-C Programming: The Big Nerd Ranch Guide — This book provides a comprehensive introduction to Objective-C, covering language basics and advanced topics. While it doesn’t focus specifically on Windows, it still serves as an excellent resource for learning Objective-C concepts.

  2. Stack Overflow — Have a specific question or problem? Stack Overflow is a fantastic community-driven question-and-answer platform where developers help each other. Search for Objective-C-related questions or ask your own – chances are, someone else has already faced a similar challenge!

  3. Apple Developer Documentation — While primarily focused on macOS and iOS development, Apple’s official documentation for Objective-C offers valuable insights and guidance that can be applied to Windows development as well. Check out their documentation for detailed language specifications and best practices.

✉️Let’s Connect!

We hope this guide has provided you with valuable insights on writing Objective-C on the Windows platform. If you have any further questions or need assistance, we’d love to help! Connect with us on social media, leave a comment below, or shoot us an email. We’re here to support your journey into Objective-C on Windows. 🌟

Now, what are you waiting for? Start coding, explore the possibilities, and let your creativity shine! 💻💡

Настройка локальной среды

Если вы все еще хотите настроить свою собственную среду для языка программирования Objective-C, вам необходимо установить Text Editor и The GCC Compiler на твоем компьютере.

Текстовый редактор

Это будет использоваться для ввода вашей программы. Примеры нескольких редакторов включают Блокнот Windows, команду редактирования ОС, Brief, Epsilon, EMACS, а также vim или vi.

Название и версия текстового редактора могут различаться в разных операционных системах. Например, Блокнот будет использоваться в Windows, а vim или vi можно использовать в Windows, а также в Linux или UNIX.

Файлы, которые вы создаете с помощью своего редактора, называются исходными файлами и содержат исходный код программы. Исходные файлы для программ Objective-C обычно имеют расширение «.m«.

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

Компилятор GCC

Исходный код, записанный в исходном файле, является удобочитаемым источником вашей программы. Его необходимо «скомпилировать», чтобы превратить в машинный язык, чтобы ваш ЦП мог действительно выполнять программу в соответствии с данными инструкциями.

Этот компилятор GCC будет использоваться для компиляции вашего исходного кода в окончательную исполняемую программу. Я предполагаю, что у вас есть базовые знания о компиляторе языков программирования.

Компилятор GCC доступен бесплатно на различных платформах, а процедура настройки на различных платформах объясняется ниже.

Установка в UNIX / Linux

Первым шагом является установка gcc вместе с пакетом gcc Objective-C. Это делается —

$ su - 
$ yum install gcc
$ yum install gcc-objc

Следующим шагом является настройка зависимостей пакетов с помощью следующей команды —

$ yum install make libpng libpng-devel libtiff libtiff-devel libobjc 
   libxml2 libxml2-devel libX11-devel libXt-devel libjpeg libjpeg-devel

Чтобы получить все возможности Objective-C, загрузите и установите GNUStep. Это можно сделать, загрузив пакет сhttp://main.gnustep.org/resources/downloads.php.

Теперь нам нужно переключиться в загруженную папку и распаковать файл:

$ tar xvfz gnustep-startup-
      
       .tar.gz 
      

Теперь нам нужно переключиться в папку gnustep-startup, которая создается с помощью —

$ cd gnustep-startup-<version>

Далее нам нужно настроить процесс сборки —

$ ./configure

Тогда мы можем построить —

$ make

Нам нужно наконец настроить среду —

$ . /usr/GNUstep/System/Library/Makefiles/GNUstep.sh

У нас есть helloWorld.m Objective-C следующим образом:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   
   NSLog (@"hello world");
   [pool drain];
   return 0;
}

Теперь мы можем скомпилировать и запустить файл Objective-C, скажем helloWorld.m, переключившись в папку, содержащую файл, с помощью компакт-диска, а затем выполнив следующие шаги:

$ gcc `gnustep-config --objc-flags` 
-L/usr/GNUstep/Local/Library/Libraries 
-lgnustep-base helloWorld.m -o helloWorld
$ ./helloWorld

Мы видим следующий результат —

2013-09-07 10:48:39.772 tutorialsPoint[12906] hello world

Установка на Mac OS

Если вы используете Mac OS X, самый простой способ получить GCC — это загрузить среду разработки Xcode с веб-сайта Apple и следовать простым инструкциям по установке. После настройки Xcode вы сможете использовать компилятор GNU для C / C ++.

Xcode в настоящее время доступен по адресу developer.apple.com/technologies/tools/ .

Установка в Windows

Чтобы запустить программу Objective-C в Windows, нам нужно установить MinGW и GNUStep Core. Оба доступны наhttps://www.gnu.org/software/gnustep/windows/installer.html.

Во-первых, нам нужно установить пакет MSYS / MinGW System. Затем нам нужно установить пакет GNUstep Core. Оба из них предоставляют установщик Windows, который не требует пояснений.

Затем используйте Objective-C и GNUstep, выбрав Пуск -> Все программы -> GNUstep -> Shell

Перейдите в папку, содержащую helloWorld.m

Мы можем скомпилировать программу, используя —

$ gcc `gnustep-config --objc-flags` 
-L /GNUstep/System/Library/Libraries hello.m -o hello -lgnustep-base -lobjc

Мы можем запустить программу, используя —

./hello.exe

Мы получаем следующий результат —

2013-09-07 10:48:39.772 tutorialsPoint[1200] hello world

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Не могу подключить сетевой принтер windows 10
  • Git checkout windows style
  • Как изменить звук загрузки windows 10
  • Ge60 msi windows 10
  • Как получить права администратора в windows 11 для удаления папки windows old