ok, I have an A level computing exam on Monday, and I have been working on the pre-release skeleton code.
This morning when I tried I got an error saying 'Sub Main' was not found
. There clearly is a Sub Main()
in the code which I will paste in below.
I tried adding another sub main()
before getting a second error saying Sub Main() has multiple definitions
.
I really need to get this sorted, so any help would be greatly appreciated.
Here is the code for the Sub Main() by itself:
Sub Main()
Dim Choice As Char
Dim Deck(52) As TCard
Dim RecentScores(NoOfRecentScores) As TRecentScore
Randomize()
Do
DisplayMenu()
Choice = GetMenuChoice()
Select Case Choice
Case "1"
LoadDeck(Deck)
ShuffleDeck(Deck)
PlayGame(Deck, RecentScores)
Case "2"
LoadDeck(Deck)
PlayGame(Deck, RecentScores)
Case "3"
DisplayRecentScores(RecentScores)
Case "4"
ResetRecentScores(RecentScores)
End Select
Loop Until Choice = "q"
End Sub
And here is the full code if that helps:
'Skeleton Program code for the AQA COMP1 Summer 2014 examination
'this code should be used in conjunction with the Preliminary Material
'written by the AQA COMP1 Programmer Team
'developed in the Visual Studio 2008 (Console Mode) programming environment (VB.NET)
Module CardPredict
Const NoOfRecentScores As Integer = 3
Structure TCard
Dim Suit As Integer
Dim Rank As Integer
End Structure
Structure TRecentScore
Dim Name As String
Dim Score As Integer
End Structure
Sub Main()
Dim Choice As Char
Dim Deck(52) As TCard
Dim RecentScores(NoOfRecentScores) As TRecentScore
Randomize()
Do
DisplayMenu()
Choice = GetMenuChoice()
Select Case Choice
Case "1"
LoadDeck(Deck)
ShuffleDeck(Deck)
PlayGame(Deck, RecentScores)
Case "2"
LoadDeck(Deck)
PlayGame(Deck, RecentScores)
Case "3"
DisplayRecentScores(RecentScores)
Case "4"
ResetRecentScores(RecentScores)
End Select
Loop Until Choice = "q"
End Sub
Sub Main()
Console.Write("Boo")
End Sub
Function GetRank(ByVal RankNo As Integer) As String
Dim Rank As String = ""
Select Case RankNo
Case 1 : Rank = "Ace"
Case 2 : Rank = "Two"
Case 3 : Rank = "Three"
Case 4 : Rank = "Four"
Case 5 : Rank = "Five"
Case 6 : Rank = "Six"
Case 7 : Rank = "Seven"
Case 8 : Rank = "Eight"
Case 9 : Rank = "Nine"
Case 10 : Rank = "Ten"
Case 11 : Rank = "Jack"
Case 12 : Rank = "Queen"
Case 13 : Rank = "King"
End Select
Return Rank
End Function
Function GetSuit(ByVal SuitNo As Integer) As String
Dim Suit As String = ""
Select Case SuitNo
Case 1 : Suit = "Clubs"
Case 2 : Suit = "Diamonds"
Case 3 : Suit = "Hearts"
Case 4 : Suit = "Spades"
End Select
Return Suit
End Function
Sub DisplayMenu()
Console.WriteLine()
Console.WriteLine("MAIN MENU")
Console.WriteLine()
Console.WriteLine("1. Play game (with shuffle)")
Console.WriteLine("2. Play game (without shuffle)")
Console.WriteLine("3. Display recent scores")
Console.WriteLine("4. Reset recent scores")
Console.WriteLine()
Console.Write("Select an option from the menu (or enter q to quit): ")
End Sub
Function GetMenuChoice() As Char
Dim Choice As Char
Choice = Console.ReadLine
Console.WriteLine()
Return Choice
End Function
Sub LoadDeck(ByRef Deck() As TCard)
Dim Count As Integer
FileOpen(1, "deck.txt", OpenMode.Input)
Count = 1
While Not EOF(1)
Deck(Count).Suit = CInt(LineInput(1))
Deck(Count).Rank = CInt(LineInput(1))
Count = Count + 1
End While
FileClose(1)
End Sub
Sub ShuffleDeck(ByRef Deck() As TCard)
Dim NoOfSwaps As Integer
Dim Position1 As Integer
Dim Position2 As Integer
Dim SwapSpace As TCard
Dim NoOfSwapsMadeSoFar As Integer
NoOfSwaps = 1000
For NoOfSwapsMadeSoFar = 1 To NoOfSwaps
Position1 = Int(Rnd() * 52) + 1
Position2 = Int(Rnd() * 52) + 1
SwapSpace = Deck(Position1)
Deck(Position1) = Deck(Position2)
Deck(Position2) = SwapSpace
Next
End Sub
Sub DisplayCard(ByVal ThisCard As TCard)
Console.WriteLine()
Console.WriteLine("Card is the " & GetRank(ThisCard.Rank) & " of " & GetSuit(ThisCard.Suit))
Console.WriteLine()
End Sub
Sub GetCard(ByRef ThisCard As TCard, ByRef Deck() As TCard, ByVal NoOfCardsTurnedOver As Integer)
Dim Count As Integer
ThisCard = Deck(1)
For Count = 1 To (51 - NoOfCardsTurnedOver)
Deck(Count) = Deck(Count + 1)
Next
Deck(52 - NoOfCardsTurnedOver).Suit = 0
Deck(52 - NoOfCardsTurnedOver).Rank = 0
End Sub
Function IsNextCardHigher(ByVal LastCard As TCard, ByVal NextCard As TCard) As Boolean
Dim Higher As Boolean
Higher = False
If NextCard.Rank > LastCard.Rank Then
Higher = True
End If
Return Higher
End Function
Function GetPlayerName() As String
Dim PlayerName As String
Console.WriteLine()
Console.Write("Please enter your name: ")
PlayerName = Console.ReadLine
Console.WriteLine()
Return PlayerName
End Function
Function GetChoiceFromUser() As Char
Dim Choice As Char
Console.Write("Do you think the next card will be higher than the last card (enter y or n)? ")
Choice = Console.ReadLine
Return Choice
End Function
Sub DisplayEndOfGameMessage(ByVal Score As Integer)
Console.WriteLine()
Console.WriteLine("GAME OVER!")
Console.WriteLine("Your score was " & Score)
If Score = 51 Then
Console.WriteLine("WOW! You completed a perfect game.")
End If
Console.WriteLine()
End Sub
Sub DisplayCorrectGuessMessage(ByVal Score As Integer)
Console.WriteLine()
Console.WriteLine("Well done! You guessed correctly.")
Console.WriteLine("Your score is now " & Score & ".")
Console.WriteLine()
End Sub
Sub ResetRecentScores(ByRef RecentScores() As TRecentScore)
Dim Count As Integer
For Count = 1 To NoOfRecentScores
RecentScores(Count).Name = ""
RecentScores(Count).Score = 0
Next
End Sub
Sub DisplayRecentScores(ByVal RecentScores() As TRecentScore)
Dim Count As Integer
Console.WriteLine()
Console.WriteLine("Recent scores:")
Console.WriteLine()
For Count = 1 To NoOfRecentScores
Console.WriteLine(RecentScores(Count).Name & " got a score of " & RecentScores(Count).Score)
Next
Console.WriteLine()
Console.WriteLine("Press the Enter key to return to the main menu")
Console.WriteLine()
Console.ReadLine()
End Sub
Sub UpdateRecentScores(ByRef RecentScores() As TRecentScore, ByVal Score As Integer)
Dim PlayerName As String
Dim Count As Integer
Dim FoundSpace As Boolean
PlayerName = GetPlayerName()
FoundSpace = False
Count = 1
While Not FoundSpace And Count <= NoOfRecentScores
If RecentScores(Count).Name = "" Then
FoundSpace = True
Else
Count = Count + 1
End If
End While
If Not FoundSpace Then
For Count = 1 To NoOfRecentScores - 1
RecentScores(Count) = RecentScores(Count + 1)
Next
Count = NoOfRecentScores
End If
RecentScores(Count).Name = PlayerName
RecentScores(Count).Score = Score
End Sub
Sub PlayGame(ByVal Deck() As TCard, ByRef RecentScores() As TRecentScore)
Dim NoOfCardsTurnedOver As Integer
Dim GameOver As Boolean
Dim NextCard As TCard
Dim LastCard As TCard
Dim Higher As Boolean
Dim Choice As Char
GameOver = False
GetCard(LastCard, Deck, 0)
DisplayCard(LastCard)
NoOfCardsTurnedOver = 1
While NoOfCardsTurnedOver < 52 And Not GameOver
GetCard(NextCard, Deck, NoOfCardsTurnedOver)
Do
Choice = GetChoiceFromUser()
Loop Until Choice = "y" Or Choice = "n"
DisplayCard(NextCard)
NoOfCardsTurnedOver = NoOfCardsTurnedOver + 1
Higher = IsNextCardHigher(LastCard, NextCard)
If Higher And Choice = "y" Or Not Higher And Choice = "n" Then
DisplayCorrectGuessMessage(NoOfCardsTurnedOver - 1)
LastCard = NextCard
Else
GameOver = True
End If
End While
If GameOver Then
DisplayEndOfGameMessage(NoOfCardsTurnedOver - 2)
UpdateRecentScores(RecentScores, NoOfCardsTurnedOver - 2)
Else
DisplayEndOfGameMessage(51)
UpdateRecentScores(RecentScores, 51)
End If
End Sub
End Module
Thanks in advance,
Ed
Permalink
Cannot retrieve contributors at this time
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid | ||||
---|---|---|---|---|---|---|---|---|---|
Learn more about: BC30420: ‘Sub Main’ was not found in ‘<name>’ |
‘Sub Main’ was not found in ‘<name>’ |
07/20/2015 |
|
|
a006d57d-4dd3-46a7-9026-ca9a31470da7 |
Sub Main
is missing, or the wrong location has been specified for it.
Error ID: BC30420
To correct this error
-
Supply the missing
Sub Main
statement, or if it exists, move it to the appropriate location in the code. For more information onSub Main
, see Main Procedure in Visual Basic. -
Specify the location of the project’s startup object in the Startup form box of the Project Designer.
See also
- Sub Statement
- Main Procedure in Visual Basic
It’s safe to say that Visual Basic has become one of the hardest languages to find content about online ever since Microsoft announced that there won’t be any more features added to it in .NET CORE/ .NET 5.
“ Going forward, we do not plan to evolve Visual Basic as a language ”
.NET Team
That explained a lot when I tried to troubleshoot an error I’d gotten and the whole of the internet was almost blank, for an error I’d call trivial and noob level. I’ve recreated the above error so as to show you how to solve it. Save you time.
Every time I tried the compile and run the project, i got and error that the Sub Main()
was not found.
The solution to this is to check that the startup form isn’t referencing to an old method. You can find that in your project properties.
- All you have to do is right-click on your main project in the top-right area of the visual basic working area.
- Scroll to the bottom and click on properties.
On the new window right at the Startup Project section is where you’re going to change from
Sub Main
to the name of your Form.
Once you’re done, you can exit that tab and re-run your project.
Everything should be working fine and you can notice that the error is gone.
Conclusion
Every day is a coding challenge. If you feel that the content was inadequate please comment about it or contact me. Keep coding. Cheers !!
- Remove From My Forums
-
Question
-
Okay, another question somewhat releated to my previous post, but I feel that it is worthy of a seperate thread.
Code Block
Module mainModule
Sub Main(ByVal args() As String)
MsgBox(«Hello Workd»)
End Sub
End ModuleWhen i type the following into the cmd prompt to compile
vbc.exe mainModule.vb /main:MainModule.vb
I get the following error
vbc : error BC30420: ‘Sub Main’ was not found in ‘mainmodule.vb’.
Why is it saying that no ‘Sub Main’ was not found when it is there?
Answers
-
Try to change the startup from Project -> Properties -> Debug Section. Hope it solves your problem
-
Code Block
Module mainModule
Sub Main()
MsgBox(«Hello Workd»)
End Sub
End Modulethis will fix your problem
-
Use the following
vbc.exe mainModule.vb
This will compile or work
or if you want to use the /main switch then use the following. The last .vb you previously had used is screwing things up. It is looking for a class name not a filename — hence the .vb is the filename not the classname.
So the following will work
vbc.exe mainModule.vb /main:MainModule
Аня_Самойлова 0 / 0 / 0 Регистрация: 24.08.2018 Сообщений: 60 |
||||
1 |
||||
01.10.2018, 19:04. Показов 8433. Ответов 10 Метки ООП (Все метки)
0 |
XIST 1293 / 994 / 141 Регистрация: 01.10.2009 Сообщений: 3,173 Записей в блоге: 1 |
||||
01.10.2018, 19:31 |
2 |
|||
Аня_Самойлова, так его и нету
0 |
0 / 0 / 0 Регистрация: 24.08.2018 Сообщений: 60 |
|
01.10.2018, 19:42 [ТС] |
3 |
На строчке 72 же объявляется
0 |
1293 / 994 / 141 Регистрация: 01.10.2009 Сообщений: 3,173 Записей в блоге: 1 |
|
01.10.2018, 19:46 |
4 |
Аня_Самойлова, именно в базовом классе его нет
0 |
ovva 4304 / 3440 / 831 Регистрация: 02.02.2013 Сообщений: 3,335 Записей в блоге: 2 |
||||
01.10.2018, 19:49 |
5 |
|||
Вынесите определение класса за границы модуля.
Если вы хотите непосредственно использовать класс КлассТовар то он не может быть MustInherit (к тому же определенные наследники нигде далее не используются).
0 |
0 / 0 / 0 Регистрация: 24.08.2018 Сообщений: 60 |
|
01.10.2018, 19:56 [ТС] |
6 |
ту же ошибку показывает(
0 |
4304 / 3440 / 831 Регистрация: 02.02.2013 Сообщений: 3,335 Записей в блоге: 2 |
|
01.10.2018, 20:07 |
7 |
Выложите ваш проект целиком.
0 |
4304 / 3440 / 831 Регистрация: 02.02.2013 Сообщений: 3,335 Записей в блоге: 2 |
|
01.10.2018, 20:24 |
8 |
Пример
0 |
Аня_Самойлова 0 / 0 / 0 Регистрация: 24.08.2018 Сообщений: 60 |
||||
01.10.2018, 20:48 [ТС] |
9 |
|||
Добавлено через 20 минут
0 |
4304 / 3440 / 831 Регистрация: 02.02.2013 Сообщений: 3,335 Записей в блоге: 2 |
|
01.10.2018, 20:58 |
10 |
Файл не открывается к сожалению Не открывается приложенный файл? Этот файл zip-архив, можно открыть любым архиватором. Внутри vb проект ConsoleApplication1 (загружается через файл ConsoleApplication1.sln).
0 |
0 / 0 / 0 Регистрация: 24.08.2018 Сообщений: 60 |
|
01.10.2018, 21:17 [ТС] |
11 |
эту проблему я решила)) файл что вы отправили действительно работает. Я постараюсь отправить свой zip
0 |
It’s actually a bit more complicated, and I fear you may have learned the wrong lesson from what DB suggested, useful though it may be.
As you might expect, every program has to know where to start. No matter what you write, it ends up being a series of VERY simple instructions, because that’s all that the CPU can do. All that higher level languages do is make it easier to create complex programs, but they all end up as a series of sequential instructions. You can see them as a stack of cards. When the program begins, it takes the first card from the stack and does what is on the card, then takes the next card from the stack and so on. It’s not quite that simple, as it can keep going back to earlier places in the stack and repeating steps, or even create a second process and move a selection of the cards over to that separate process so that both are going through their stacks of cards at the same time.
However, there always has to be that first card. By long standing tradition, that is Sub Main(). For a very long time, you could ALWAYS find Sub Main(), and that would be roughly where things started (some memory could be set up ahead of time, but nothing much). The first line in Sub Main was the first card in the stack.
With Windows programming in .NET, there is ALWAYS a Sub Main….but you can’t ALWAYS find it. You used to be able to, back in .NET 2002 and 2003, but since then it could be hidden. Windows programs usually begin with a startup form, in which case you’d have a hard time finding Sub Main, if you even can.
What DB showed you is the style that Windows applications had to follow back in 2002 and 2003, and which is still used for console apps as he demonstrated. If you create a Windows application rather than a console app, then you’ll have a startup form (which is usually the first one given to you, by default, though you are free to change that), and neither the module nor the Sub Main is necessary. In that case, the code you had would be fine as you had it, but you’d also have a startup form, which would hide the Sub Main from you.
A class library is a dll. You’ve doubtless seen a few items with that extension. The key point about a dll is that it doesn’t have a Sub Main, plain or hidden. Therefore, you can’t execute a dll because there is no starting point in it. Using the stack of cards analogy, you could say that a dll is one or more stacks of cards, but none of them is the first one. That type of project holds code and objects that will be used by one or more other projects. They can’t stand alone, because they can’t start on their own. They have to be included into some project that actually has a starting point. Once included in, they can be used by that other project. Typically, you create a dll to store methods and objects that you feel you’ll be able to use in multiple projects, though there are other uses for them, as well.
So, don’t feel that you MUST have a module and a Sub Main. You must have one for a console app, but need not write either one for a Windows forms app, and can’t have a meaningful Sub Main for a class library.
Jujube
Пользователь
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Короче надо скопилировать код в Visual Studio, но мне выдает ошибку Ошибка 1 В «1» не найден метод Sub Main. 1 в программирование вообще ничего не понимаю, только начал.
ап
Misha_t
Пользователь
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Давай по порядку.
Какой язык, откуда качал студию?
Jujube
Пользователь
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Misha_t сказал(а):↑
Давай по порядку.
Какой язык, откуда качал студию?Нажмите, чтобы раскрыть…
C++
С офф сайта майков
Darknezz
Пользователь
Регистрация:
29.03.2012
Сообщения: 574
Рейтинг: 245
Регистрация:
29.03.2012
Сообщения: 574
Рейтинг: 245
umad555
Пользователь
Регистрация:
19.10.2013
Сообщения: 1036
Рейтинг: 470
Нарушения: 100
Регистрация:
19.10.2013
Сообщения: 1036
Рейтинг: 470
Нарушения: 100
И что такое гугл тоже не знаешь? …
Jujube
Пользователь
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Darknezz сказал(а):↑
Нажмите, чтобы раскрыть…
#include
using namespace std;
int main()
{
cout << «Hello, world!» << endl;
system(«pause»);
return 0;
}umad555 сказал(а):↑
И что такое гугл тоже не знаешь? …
Нажмите, чтобы раскрыть…
гугл изнасиловал во все щели
Misha_t
Пользователь
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Хмм, попробуй не подключать стд, а вместо потоков cout используй printf. Компилит? И паузу убери.
Jujube
Пользователь
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Misha_t сказал(а):↑
Хмм, попробуй не подключать стд, а вместо потоков cout используй printf. Компилит?
Нажмите, чтобы раскрыть…
если ты имеешь ввиду удалить using namespace std; и написать так printf << «Hello, world!» << endl;, то все равно так же ошибка
Misha_t
Пользователь
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Не совсем это,но раз ошибка та же то пофиг. Сустем удалял?
Jujube
Пользователь
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
МБ лучше что-то увидите
Misha_t сказал(а):↑
Не совсем это но не суть, паузу удалял?
Нажмите, чтобы раскрыть…
неа
Follows
Пользователь
Регистрация:
18.06.2013
Сообщения: 2058
Рейтинг: 944
Регистрация:
18.06.2013
Сообщения: 2058
Рейтинг: 944
Jujube
Пользователь
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Misha_t сказал(а):↑
Не совсем это,но раз ошибка та же то пофиг. Сустем удалял?
Нажмите, чтобы раскрыть…
нет
Follows сказал(а):↑
Нажмите, чтобы раскрыть…
Ты иди и скажи это в лицо упертой visual studii
Follows
Пользователь
Регистрация:
18.06.2013
Сообщения: 2058
Рейтинг: 944
Регистрация:
18.06.2013
Сообщения: 2058
Рейтинг: 944
Открой настройки проекта и сделай скрин.
Плюс, если не пишешь большие проекты, скачай DEV-C++ и не усложняй себе жизнь.
aiseli
Пользователь
Регистрация:
06.03.2013
Сообщения: 892
Рейтинг: 467
Регистрация:
06.03.2013
Сообщения: 892
Рейтинг: 467
«Int main», а в мейне ничего не возвращает.
Напиши вместо «инт» «void main()».
Misha_t
Пользователь
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Ощущение что ты создаешь не сишный проект.
Follows
Пользователь
Регистрация:
18.06.2013
Сообщения: 2058
Рейтинг: 944
Регистрация:
18.06.2013
Сообщения: 2058
Рейтинг: 944
aiseli сказал(а):↑
«Int main», а в мейне ничего не возвращает.
Напиши вместо «инт» «void main()».Нажмите, чтобы раскрыть…
return 0 видишь?
Jujube
Пользователь
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Follows сказал(а):↑
Открой настройки проекта и сделай скрин.
Плюс, если не пишешь большие проекты, скачай DEV-C++ и не усложняй себе жизнь.Нажмите, чтобы раскрыть…
свойства? я там покапался и сделал «автоматически запускаемый объект sub main»
![]()
Misha_t
Пользователь
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
aiseli сказал(а):↑
«Int main», а в мейне ничего не возвращает.
Напиши вместо «инт» «void main()».Нажмите, чтобы раскрыть…
void main — безграмотность.
А так даже если return 0 не было б код ошибки другой был бы
aiseli
Пользователь
Регистрация:
06.03.2013
Сообщения: 892
Рейтинг: 467
Регистрация:
06.03.2013
Сообщения: 892
Рейтинг: 467
Misha_t сказал(а):↑
void main — безграмотность.
А так даже если return 0 не было б код ошибки другой был быНажмите, чтобы раскрыть…
Ну я думаю, что ошибка заключается в функции мейне. Для хеллоу ворлда и Войд Мейн подойдет…. Но по сути, эту ошибку вижу в 1 раз.
Follows
Пользователь
Регистрация:
18.06.2013
Сообщения: 2058
Рейтинг: 944
Регистрация:
18.06.2013
Сообщения: 2058
Рейтинг: 944
Jujube сказал(а):↑
свойства? я там покапался и сделал «автоматически запускаемый объект sub main»
Нажмите, чтобы раскрыть…
Создавай c++ консольное приложение, а не c# Windows forms.
Jujube
Пользователь
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
aiseli сказал(а):↑
Ну я думаю, что ошибка заключается в функции мейне. Для хеллоу ворлда и Войд Мейн подойдет…. Но по сути, эту ошибку вижу в 1 раз.
Нажмите, чтобы раскрыть…
мда начал курсы программирования и застрял на первом уроке, похоже на меня
Misha_t
Пользователь
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Вообще sub main это что-то про бейсик вроде) Или шарп максимум)
Jujube
Пользователь
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Регистрация:
22.02.2014
Сообщения: 335
Рейтинг: 261
Follows сказал(а):↑
Создавай c++ консольное приложение, а не c# Windows forms.
Нажмите, чтобы раскрыть…
молю расскажи на русском языке
ilexandr
Пользователь
Регистрация:
13.02.2014
Сообщения: 7
Рейтинг: 0
Регистрация:
13.02.2014
Сообщения: 7
Рейтинг: 0
у тебя проет Visual Basic, а не С++. конечно он выдаст ошибку, там синтаксис другой.
создай проект заново и скопируй свой код в него, все должно заработать
Misha_t
Пользователь
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Регистрация:
23.08.2012
Сообщения: 474
Рейтинг: 124
Jujube сказал(а):↑
молю расскажи на русском языке
Нажмите, чтобы раскрыть…
Заходи сейчас Файл-Создать — Проэкт (Ctrl-Shift-N хоткей) выбирай шаблоны, VIsual C++, общие, пустой проэкт.
Тема закрыта
-
Заголовок
Ответов Просмотров
Последнее сообщение
-
Сообщений: 12
09 Jun 2023 в 05:08Сообщений:12
Просмотров:21
-
Сообщений: 19
09 Jun 2023 в 03:13Сообщений:19
Просмотров:60
-
Сообщений: 18
09 Jun 2023 в 03:07Сообщений:18
Просмотров:51
-
Сообщений: 6
09 Jun 2023 в 02:54Сообщений:6
Просмотров:23
-
Сообщений: 3
09 Jun 2023 в 02:42Сообщений:3
Просмотров:17
It’s actually a bit more complicated, and I fear you may have learned the wrong lesson from what DB suggested, useful though it may be.
As you might expect, every program has to know where to start. No matter what you write, it ends up being a series of VERY simple instructions, because that’s all that the CPU can do. All that higher level languages do is make it easier to create complex programs, but they all end up as a series of sequential instructions. You can see them as a stack of cards. When the program begins, it takes the first card from the stack and does what is on the card, then takes the next card from the stack and so on. It’s not quite that simple, as it can keep going back to earlier places in the stack and repeating steps, or even create a second process and move a selection of the cards over to that separate process so that both are going through their stacks of cards at the same time.
However, there always has to be that first card. By long standing tradition, that is Sub Main(). For a very long time, you could ALWAYS find Sub Main(), and that would be roughly where things started (some memory could be set up ahead of time, but nothing much). The first line in Sub Main was the first card in the stack.
With Windows programming in .NET, there is ALWAYS a Sub Main….but you can’t ALWAYS find it. You used to be able to, back in .NET 2002 and 2003, but since then it could be hidden. Windows programs usually begin with a startup form, in which case you’d have a hard time finding Sub Main, if you even can.
What DB showed you is the style that Windows applications had to follow back in 2002 and 2003, and which is still used for console apps as he demonstrated. If you create a Windows application rather than a console app, then you’ll have a startup form (which is usually the first one given to you, by default, though you are free to change that), and neither the module nor the Sub Main is necessary. In that case, the code you had would be fine as you had it, but you’d also have a startup form, which would hide the Sub Main from you.
A class library is a dll. You’ve doubtless seen a few items with that extension. The key point about a dll is that it doesn’t have a Sub Main, plain or hidden. Therefore, you can’t execute a dll because there is no starting point in it. Using the stack of cards analogy, you could say that a dll is one or more stacks of cards, but none of them is the first one. That type of project holds code and objects that will be used by one or more other projects. They can’t stand alone, because they can’t start on their own. They have to be included into some project that actually has a starting point. Once included in, they can be used by that other project. Typically, you create a dll to store methods and objects that you feel you’ll be able to use in multiple projects, though there are other uses for them, as well.
So, don’t feel that you MUST have a module and a Sub Main. You must have one for a console app, but need not write either one for a Windows forms app, and can’t have a meaningful Sub Main for a class library.