Меню

Ошибка 1 error lnk1561 точка входа должна быть определена

Что означает эта ошибка?

1> LINK : не найден или не выполнена сборка c:userscsdocumentsvisual studio 2010ProjectsролролглDebugVwe.exe при последней инкрементной компоновке; выполняется полная компоновка
1>LINK : fatal error LNK1561: точка входа должна быть определена

Nicolas Chabanovsky's user avatar

задан 22 фев 2012 в 17:29

RconPro's user avatar

Возможно вы создали пустой проект, пользуясь мастером Visual Studio, и пытаетесь его скомпилировать и слинковать. А так как он не имеет метода main (для консольного приложения) и т.п., то сборщик и сообщает об ошибке.

Либо используйте другой шаблон проекта, либо добавьте в проект файл содержащий точку входа.

ответ дан 22 фев 2012 в 17:46

stanislav's user avatar

stanislavstanislav

34.1k25 золотых знаков95 серебряных знаков212 бронзовых знаков

Правая кнопка мыши на Проект -> Свойства -> Компоновщик -> Все параметры -> Подсистема.
Выберите — «Консоль».
Также не забудьте о main();

Denis's user avatar

Denis

8,84010 золотых знаков28 серебряных знаков54 бронзовых знака

ответ дан 12 мая 2016 в 12:39

Little Fox's user avatar

Little FoxLittle Fox

5944 серебряных знака18 бронзовых знаков

2

Если у тебя консольное приложение, надо определить main, а если оконное приложение Windows, то WinMain.

ответ дан 23 фев 2012 в 7:42

devoln's user avatar

devolndevoln

5,38120 серебряных знаков31 бронзовый знак

Александр Зубов

0 / 0 / 0

Регистрация: 06.02.2013

Сообщений: 4

1

06.02.2013, 19:30. Показов 7149. Ответов 6

Метки нет (Все метки)


вот текст программы:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "stdafx.h"
#include "iostream"
#include "conio.h"
#include "math.h"
#include "stdio.h"
 
using namespace std;
 
double F(double x)
{
    return pow(x, 3) - x + exp(-x);
}
void fibonachi(double a, double b, double e)
{
    FILE *fibon;
    fibon=fopen("C://Информатика//Fibonachi.txt", "w");
    fprintf(fibon, "Итер|  (a+b)/2   |  F((a+b)/2) |     a       |     b     |n");
    fprintf(fibon, "----------------------------------------------------------n");
 
    int fib[80]; //задаем массив с числами Фибоначчи
 
    fib[0]=1; fib[1]=1; //в первые два элемента массива записываем 1, так начинается последовательность Фибоначчи
    int i=1;
     while ( (b-a)/e >fib[i])
       {
        i++; fib[i]=fib[i-2] + fib[i-1];
       }
    double l=a+fib[i-2]*(b-a) / fib[i], m=a+fib[i-1]*(b-a)/fib[i], d1=F(l), d2=F(m);
    for (int k=i-1; k>=2; k--)
    {
      fprintf(fibon, "%3d | %6.6f  |  %6.6f  | [%6.6f, | %6.6f]|n",i-k,(a+b)/2, F((a+b)/2), a, b);
      if (d1<d2)
        {
         b=m; m=l; d2=F(l);
         l=a+fib[k-2]*(b-a)/fib[k];
         d1=F(l);
        }
       else
        {
         a=l; l=m; d1=d2;
         m=a+fib[k-1]*(b-a)/fib[k];
         d2=F(m);
        }
    }
    fprintf(fibon,"Итераций:%3dnКонечные значения: x=%6.6f  y=%6.6f",i-2, (a+b)/2, F((a+b)/2));
}

и вот вывод:

Код

1>------ Построение начато: проект: Fibbo, Конфигурация: Debug Win32 ------
1>  Fibbo.cpp
1>Fibbo.cpp(17): warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1>          C:Program Files (x86)Microsoft Visual Studio 10.0VCincludestdio.h(234): см. объявление "fopen"
1>Fibbo.cpp(46): warning C4129: :
1>LINK : fatal error LNK1561: точка входа должна быть определена
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

как понимаю, ошибка:1>LINK : fatal error LNK1561: точка входа должна быть определена

помогите пожалуйста, как исправить?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

06.02.2013, 19:30

6

погромист

414 / 250 / 30

Регистрация: 27.08.2012

Сообщений: 550

06.02.2013, 19:44

2

Где main()?



0



0 / 0 / 0

Регистрация: 06.02.2013

Сообщений: 4

06.02.2013, 19:45

 [ТС]

3

Цитата
Сообщение от Александр Зубов
Посмотреть сообщение

void fibonachi(double a, double b, double e)

я же вот как ввожу.
просто не понимаю, куда его тут вставить?!



0



coloc

погромист

414 / 250 / 30

Регистрация: 27.08.2012

Сообщений: 550

06.02.2013, 19:47

4

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "iostream"
#include "conio.h"
#include "math.h"
#include "stdio.h"
 
using namespace std;
 
double F(double x)
{
return pow(x, 3) - x + exp(-x);
}
void fibonachi(double a, double b, double e)
{
FILE *fibon;
fibon=fopen("C://Èíôîðìàòèêà//Fibonachi.txt", "w");
fprintf(fibon, "Èòåð| (a+b)/2 | F((a+b)/2) | a | b |n");
fprintf(fibon, "----------------------------------------------------------n");
 
int fib[80]; //çàäàåì ìàññèâ ñ ÷èñëàìè Ôèáîíà÷÷è
 
fib[0]=1; fib[1]=1; //â ïåðâûå äâà ýëåìåíòà ìàññèâà çàïèñûâàåì 1, òàê íà÷èíàåòñÿ ïîñëåäîâàòåëüíîñòü Ôèáîíà÷÷è
int i=1;
while ( (b-a)/e >fib[i])
{
i++; fib[i]=fib[i-2] + fib[i-1];
}
double l=a+fib[i-2]*(b-a) / fib[i], m=a+fib[i-1]*(b-a)/fib[i], d1=F(l), d2=F(m);
for (int k=i-1; k>=2; k--)
{
fprintf(fibon, "%3d | %6.6f | %6.6f | [%6.6f, | %6.6f]|n",i-k,(a+b)/2, F((a+b)/2), a, b);
if (d1<d2)
{
b=m; m=l; d2=F(l);
l=a+fib[k-2]*(b-a)/fib[k];
d1=F(l);
}
else
{
a=l; l=m; d1=d2;
m=a+fib[k-1]*(b-a)/fib[k];
d2=F(m);
}
}
fprintf(fibon,"Èòåðàöèé:%3dnÊîíå÷íûå çíà÷åíèÿ: x=%6.6f y=%6.6f",i-2, (a+b)/2, F((a+b)/2));
}
 
int main(){
    
    fibonachi(13, 2, 3);
    return 0;
}

в мейн пишите функции



1



0 / 0 / 0

Регистрация: 06.02.2013

Сообщений: 4

06.02.2013, 19:51

 [ТС]

5

А вы запустите программу.
Там получается число итераций -1
что-то не то..

Добавлено через 50 секунд
и почему такие числа??

Цитата
Сообщение от coloc
Посмотреть сообщение

fibonachi(13, 2, 3);



0



погромист

414 / 250 / 30

Регистрация: 27.08.2012

Сообщений: 550

06.02.2013, 19:54

6

Ну уже сами разбирайтесь что не то. Вы написали какая у вас ошибка — я ответил. Или вы скопипастили пример и даже не знаете какие параметры этой функции передать?

Добавлено через 58 секунд

Цитата
Сообщение от Александр Зубов
Посмотреть сообщение

и почему такие числа??

Метод тыка



0



0 / 0 / 0

Регистрация: 06.02.2013

Сообщений: 4

06.02.2013, 19:55

 [ТС]

7

Цитата
Сообщение от coloc
Посмотреть сообщение

Или вы скопипастили пример и даже не знаете какие параметры этой функции передать?

нет, сам писал
спасибо за main



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

06.02.2013, 19:55

7

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Linker Tools Error LNK1561

Linker Tools Error LNK1561

11/04/2016

LNK1561

LNK1561

cb0b709b-7c9c-4496-8a4e-9e1e4aefe447

entry point must be defined

The linker did not find an entry point, the initial function to call in your executable. By default, the linker looks for a main or wmain function for a console app, a WinMain or wWinMain function for a Windows app, or DllMain for a DLL that requires initialization. You can specify another function by using the /ENTRY linker option.

This error can have several causes:

  • You may not have included the file that defines your entry point in the list of files to link. Verify that the file that contains the entry point function is linked into your app.
  • You may have defined the entry point using the wrong function signature; for example, you may have misspelled or used the wrong case for the function name, or specified the return type or parameter types incorrectly.
  • You may not have specified the /DLL option when building a DLL.
  • You may have specified the name of the entry point function incorrectly when you used the /ENTRY linker option.
  • If you are using the LIB tool to build a DLL, you may have specified a .def file. If so, remove the .def file from the build.

When building an app, the linker looks for an entry point function to call to start your code. This is the function that is called after the app is loaded and the runtime is initialized. You must supply an entry point function for an app, or your app can’t run. An entry point is optional for a DLL. By default, the linker looks for an entry point function that has one of several specific names and signatures, such as int main(int, char**). You can specify another function name as the entry point by using the /ENTRY linker option.

Example

The following sample generates LNK1561:

// LNK1561.cpp
// LNK1561 expected
int i;
// add a main function to resolve this error

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Linker Tools Error LNK1561

Linker Tools Error LNK1561

11/04/2016

LNK1561

LNK1561

cb0b709b-7c9c-4496-8a4e-9e1e4aefe447

entry point must be defined

The linker did not find an entry point, the initial function to call in your executable. By default, the linker looks for a main or wmain function for a console app, a WinMain or wWinMain function for a Windows app, or DllMain for a DLL that requires initialization. You can specify another function by using the /ENTRY linker option.

This error can have several causes:

  • You may not have included the file that defines your entry point in the list of files to link. Verify that the file that contains the entry point function is linked into your app.
  • You may have defined the entry point using the wrong function signature; for example, you may have misspelled or used the wrong case for the function name, or specified the return type or parameter types incorrectly.
  • You may not have specified the /DLL option when building a DLL.
  • You may have specified the name of the entry point function incorrectly when you used the /ENTRY linker option.
  • If you are using the LIB tool to build a DLL, you may have specified a .def file. If so, remove the .def file from the build.

When building an app, the linker looks for an entry point function to call to start your code. This is the function that is called after the app is loaded and the runtime is initialized. You must supply an entry point function for an app, or your app can’t run. An entry point is optional for a DLL. By default, the linker looks for an entry point function that has one of several specific names and signatures, such as int main(int, char**). You can specify another function name as the entry point by using the /ENTRY linker option.

Example

The following sample generates LNK1561:

// LNK1561.cpp
// LNK1561 expected
int i;
// add a main function to resolve this error

LINK: фатальная ошибка LNK1561: точка входа должна быть определена ERROR IN VС++

29 SortOf [2013-06-12 19:12:00]

Я впервые установил MS VS VC++, чтобы начать программировать OpenGL с библиотекой GLFW. Я следую инструкциям по его установке на http://shawndeprey.blogspot.com/2012/02/setting-up-glfw-in-visual-studio-2010.html Затем я написал эту простую программу, просто чтобы протестировать ее, который работал на Eclipse:

Но потом я получил эту ужасную ошибку:

Я знаю, что я искал в Интернете, и единственное решение, которое я нашел, было «Для работы требуется функция main() «. У меня, очевидно, есть это, прямо там, но это все еще бросает мне ту же самую фатальную ошибку 🙁

Было бы здорово получить ответ о том, как это исправить. Может быть, у меня есть недостатки в процессе установки или что-то в этом роде.

c++ visual-c++ visual-studio

10 ответов

Это проект консоли или проект Windows? Я спрашиваю, потому что для Win32 и аналогичного проекта точка входа WinMain() .

  • Щелкните правой кнопкой мыши проект (а не решение) с левой стороны.
  • Затем нажмите «Свойства» → «Свойства конфигурации» → «Линкер» → «Система»

Если он говорит Subsystem Windows , ваша точка входа должна быть WinMain(), т.е.

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

Он даже не доходит до того, что загружается и выполняется.

8 ash [2013-06-12 19:44:00]

Невозможно найти точку входа для вашей программы, в данном случае main() . Вероятно, ваши настройки компоновщика неверны.

В моем случае программа работала нормально, а потом, через день, я просто столкнулся с этой проблемой, ничего не делая.

Решение, которое сработало (до редактирования область была пуста):

измените его на Консоль (/SUBSYSTEM: CONSOLE), она будет работать

Вы можете получить эту ошибку, если вы определяете проект как .exe, но хотите создать .lib или .dll

0 sdff [2015-10-29 04:15:00]

У меня это произошло на VS после того, как я изменил окончание строки файла. Изменение их обратно в Windows CR LF исправило проблему.

0 lizard [2018-07-31 20:44:00]

Главное отсутствовало в конфигурации точки входа.

0 Brackets [2016-12-30 20:51:00]

В Visual Studio: Свойства -> Расширенные -> Точка входа -> записать только имя функции, с которой программа должна начинаться, с учетом регистра, без каких-либо скобок и аргументов командной строки.

0 dude [2017-10-09 18:51:00]

Если у кого-то возникли проблемы с этим, я сам получил один пустой .cpp файл в другом проекте даже (но в том же решении) и просто дал ему простой main с возвратом 0; и затем работал хорошо.

Я только что узнал, что в моем коде функция int main() не была включена, и это было: int choice() и еще одна, называемая int choice() внутри первой. Тогда проблем может быть 2: вы должны включить функцию int main(), или вы не можете иметь две переменные/функции или объявления (int, string, char, double, float, double float. ) в одной и той же функции, Я хочу сказать, что я просто думаю, потому что я просто пишу для развлечения и никогда не учился c++.

Вот мой код:

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int x;
    int y = pow(2, x);
    cin>>x;
    cout<< y;
    system("pause");
    return 0;
}

Почему я получаю ошибку компиляции? LNK1561 entry point must be defined

Я использую Visual Studio Express.

2 ответа

Лучший ответ

Вам нужно присвоить значение x перед его использованием

int x;
int y = pow(2, x); // <--- what is the value of x here?

Сначала попробуйте получить значение x из ввода.

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int x;
    cin >> x;
    int y = pow(2, x);
    cout<< y; 
    system("pause");
    return 0;
}


4

Inisheer
8 Май 2016 в 05:15

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int x;
    //int y = pow(2, x);//(1)
    //cin>>x;//(2)

    //exchange the lines (2) and (1)
    cin>>x;//(2)
    int y = pow(2, x);//(1)
    cout<< y; 
    system("pause");
    return 0;
}

Я создал пустой проект Visual C ++ с Visual Studio 2017 15.3.4 Редакция сообщества, выбрав Visual C ++ -> Общие -> Пустой проект из мастера. Я хотел создать библиотеку C ++ (статическую или динамическую).

Но когда я компилирую это, я получаю это сообщение:

ССЫЛКА: фатальная ошибка LNK1561: должна быть определена точка входа

Я щелкнул правой кнопкой мыши на Project, выберите Properties, Linker и Advanced, и опция Entry Point пуста.

Что я должен положить туда?

Есть ли еще лучший вариант для создания библиотеки C ++?

2

Решение

Библиотека не имеет точки входа, поэтому вы можете сказать, что проект настроен неправильно. Конкретный параметр, который вы забыли изменить, — это «Проект»> «Свойства»> «Основные»> «Тип конфигурации». Выберите «Статическая библиотека (.lib)».

Это пошло не так, потому что вы начали с нуля, правильная настройка десятков настроек никогда не была проблемой. Для VS2017 RTM вы предпочитаете начинать с Win32> Win32 Project> Next> «Статическая библиотека». Возможно, это изменилось, я не обновлял его, потому что видел слишком много неприятных отчетов об ошибках для 15.3.x

1

Другие решения

Чтобы создать статическую библиотеку в VS 2017 версии 15.3.4, сначала выберите шаблон «Мастер рабочего стола Windows»,

введите описание изображения здесь

В появившемся диалоговом окне мастера измените тип приложения на статическую библиотеку:

введите описание изображения здесь

Вы также можете отключить предварительно скомпилированные заголовки, поскольку в Visual C ++ это дает нестандартное поведение препроцессора.

2

  • Question

  • I am trying to make an executable from source code, headers, etc.

    I am using Visual Studio 10.0.

    I get this message.

    Can someone help me?

    Thanks.

    LINK : fatal error LNK1561: entry point must be defined

All replies

  • Raleigh77 wrote:

    I am trying to make an executable from source code, headers, etc.

    LINK : fatal error LNK1561: entry point must be defined

    You haven’t defined a function named main or wmain or WinMain or  wWinMain.


    Igor Tandetnik

  • If please possible quote the program or just the part of program which consist your entry point of your program. i.e. the part of program having the Main() fuction is it is a console program, the cmd type. or WinMain() function
    if a windows program. If there isn’t one such function then thats is your problem. Your program must have a entry point fuction in other words the function from which your program starts. There might be a possibilty you might have misstyped the fuction name
    incorrectly.

    • Proposed as answer by

      Tuesday, November 22, 2011 4:39 AM

  • >There might be a possibilty you might have misstyped
    >the fuction name incorrectly.

    <evil grin> As you did when you typed:

    >…the part of program which consist your entry point
    >of your program. i.e. the part of program having the
    >Main() fuction is it is a console program …

    It should be: «main() function …»

    C and C++ are case-sensitive languages. The names
    «main» and «Main» are not the same.

    — Wayne

    • Proposed as answer by
      detectivecalcite
      Thursday, October 4, 2012 6:14 AM

  • Thanks.

    This came from here.

    http://msdn.microsoft.com/en-us/library/aa363680%28v=vs.85%29.aspx

    Andy

    // report_event
    #ifndef UNICODE
    #define UNICODE
    #endif
    #include <windows.h>
    #include <stdio.h>
    #include «provider.h»

    #pragma comment(lib, «advapi32.lib»)

    #define PROVIDER_NAME L»MyEventProvider»

    // Hardcoded insert string for the event messages.
    CONST LPWSTR pBadCommand = L»The command that was not valid»;
    CONST LPWSTR pFilename = L»c:\folder\file.ext»;
    CONST LPWSTR pNumberOfRetries = L»3″;
    CONST LPWSTR pSuccessfulRetries = L»0″;
    CONST LPWSTR pQuarts = L»8″;
    CONST LPWSTR pGallons = L»2″;

    void wmain(void)
    {
        HANDLE hEventLog = NULL;
        LPWSTR pInsertStrings[2] = {NULL, NULL};
        DWORD dwEventDataSize = 0;

        // The source name (provider) must exist as a subkey of Application.
        hEventLog = RegisterEventSource(NULL, PROVIDER_NAME);
        if (NULL == hEventLog)
        {
            wprintf(L»RegisterEventSource failed with 0x%x.n», GetLastError());
            goto cleanup;
        }

        // This event includes user-defined data as part of the event. The event message
        // does not use insert strings.
        dwEventDataSize = ((DWORD)wcslen(pBadCommand) + 1) * sizeof(WCHAR);
        if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, UI_CATEGORY, MSG_INVALID_COMMAND, NULL, 0, dwEventDataSize, NULL, pBadCommand))
        {
            wprintf(L»ReportEvent failed with 0x%x for event 0x%x.n», GetLastError(), MSG_INVALID_COMMAND);
            goto cleanup;
        }

        // This event uses insert strings.
        pInsertStrings[0] = pFilename;
        if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, DATABASE_CATEGORY, MSG_BAD_FILE_CONTENTS, NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL))
        {
            wprintf(L»ReportEvent failed with 0x%x for event 0x%x.n», GetLastError(), MSG_BAD_FILE_CONTENTS);
            goto cleanup;
        }

        // This event uses insert strings.
        pInsertStrings[0] = pNumberOfRetries;
        pInsertStrings[1] = pSuccessfulRetries;
        if (!ReportEvent(hEventLog, EVENTLOG_WARNING_TYPE, NETWORK_CATEGORY, MSG_RETRIES, NULL, 2, 0, (LPCWSTR*)pInsertStrings, NULL))
        {
            wprintf(L»ReportEvent failed with 0x%x for event 0x%x.n», GetLastError(), MSG_RETRIES);
            goto cleanup;
        }

        // This event uses insert strings.
        pInsertStrings[0] = pQuarts;
        pInsertStrings[1] = pGallons;
        if (!ReportEvent(hEventLog, EVENTLOG_INFORMATION_TYPE, UI_CATEGORY, MSG_COMPUTE_CONVERSION, NULL, 2, 0, (LPCWSTR*)pInsertStrings, NULL))
        {
            wprintf(L»ReportEvent failed with 0x%x for event 0x%x.n», GetLastError(), MSG_COMPUTE_CONVERSION);
            goto cleanup;
        }

        wprintf(L»All events successfully reported.n»);

    cleanup:

        if (hEventLog)
            DeregisterEventSource(hEventLog);
    }

  • I am using Visual Studio 10.0.

    I get this message.

    LINK : fatal error LNK1561: entry point must be defined

    The code came from here.

    http://msdn.microsoft.com/en-us/library/aa363680%28v=vs.85%29.aspx

    Could someone help me with this problem?

    Thanks.

    // report_event
    #ifndef UNICODE
    #define UNICODE
    #endif
    #include <windows.h>
    #include <stdio.h>
    #include «provider.h»

    #pragma comment(lib, «advapi32.lib»)

    #define PROVIDER_NAME L»MyEventProvider»

    // Hardcoded insert string for the event messages.
    CONST LPWSTR pBadCommand = L»The command that was not valid»;
    CONST LPWSTR pFilename = L»c:\folder\file.ext»;
    CONST LPWSTR pNumberOfRetries = L»3″;
    CONST LPWSTR pSuccessfulRetries = L»0″;
    CONST LPWSTR pQuarts = L»8″;
    CONST LPWSTR pGallons = L»2″;

    void wmain(void)
    {
        HANDLE hEventLog = NULL;
        LPWSTR pInsertStrings[2] = {NULL, NULL};
        DWORD dwEventDataSize = 0;

        // The source name (provider) must exist as a subkey of Application.
        hEventLog = RegisterEventSource(NULL, PROVIDER_NAME);
        if (NULL == hEventLog)
        {
            wprintf(L»RegisterEventSource failed with 0x%x.n», GetLastError());
            goto cleanup;
        }

        // This event includes user-defined data as part of the event. The event message
        // does not use insert strings.
        dwEventDataSize = ((DWORD)wcslen(pBadCommand) + 1) * sizeof(WCHAR);
        if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, UI_CATEGORY, MSG_INVALID_COMMAND, NULL, 0,

    dwEventDataSize, NULL, pBadCommand))
        {
            wprintf(L»ReportEvent failed with 0x%x for event 0x%x.n», GetLastError(),

    MSG_INVALID_COMMAND);
            goto cleanup;
        }

        // This event uses insert strings.
        pInsertStrings[0] = pFilename;
        if (!ReportEvent(hEventLog, EVENTLOG_ERROR_TYPE, DATABASE_CATEGORY, MSG_BAD_FILE_CONTENTS,

    NULL, 1, 0, (LPCWSTR*)pInsertStrings, NULL))
        {
            wprintf(L»ReportEvent failed with 0x%x for event 0x%x.n», GetLastError(),

    MSG_BAD_FILE_CONTENTS);
            goto cleanup;
        }

        // This event uses insert strings.
        pInsertStrings[0] = pNumberOfRetries;
        pInsertStrings[1] = pSuccessfulRetries;
        if (!ReportEvent(hEventLog, EVENTLOG_WARNING_TYPE, NETWORK_CATEGORY, MSG_RETRIES, NULL, 2, 0,

    (LPCWSTR*)pInsertStrings, NULL))
        {
            wprintf(L»ReportEvent failed with 0x%x for event 0x%x.n», GetLastError(), MSG_RETRIES);
            goto cleanup;
        }

        // This event uses insert strings.
        pInsertStrings[0] = pQuarts;
        pInsertStrings[1] = pGallons;
        if (!ReportEvent(hEventLog, EVENTLOG_INFORMATION_TYPE, UI_CATEGORY, MSG_COMPUTE_CONVERSION,

    NULL, 2, 0, (LPCWSTR*)pInsertStrings, NULL))
        {
            wprintf(L»ReportEvent failed with 0x%x for event 0x%x.n», GetLastError(),

    MSG_COMPUTE_CONVERSION);
            goto cleanup;
        }

        wprintf(L»All events successfully reported.n»);

    cleanup:

        if (hEventLog)
            DeregisterEventSource(hEventLog);
    }

    • Merged by
      lucy-liu
      Wednesday, February 9, 2011 3:11 AM
      Merge them to keep in the same topic

  • Configuration Properties, Linker, System, SubSystem => set to Console (/SUBSYSTEM:CONSOLE)

  • Configuration Properties, Linker, System, SubSystem => set to Console (/SUBSYSTEM:CONSOLE)

    Duplicate post.

  • Thanks.

    I uninstalled V.S. because of the difficulty of using it.

    I used the Pro version, and it took about 6 hrs. to download and install.

    I am rethinking if it would be worth the time and effort for what I would probably use

    for only one C ++ source.

    I currently use masm and it’s linker to produce 32 bit programs using assembly source code.

    Andy

  • Hi Raleigh77,

    Have you solved your issue?

    If you have solved, please mark the useful reply as answer.

    Best regards,

    Lucy


    Lucy Liu [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • No help has worked. Does someone have some working code in C that uses ReportEvent? Thanks.

  • >Does someone have some working code in C that uses ReportEvent?

    The code from the URL you posted compiles without errors or
    warnings for me using VC++ 2008 Express.

    You need to supply more information about what you are
    doing and how you are doing it, if you want detailed
    help. You have made no mention of *exactly* how you
    have tried to build this example. From the IDE?
    From the command line? If IDE, using which Project
    Template? If from the command line, what was the
    actual and complete command used?

    — Wayne

  • I have the required dll file and header file for the project.

    I used the 2003 PSDK to make those.

    I believe in order to test if it works would require changing the path to that dll file.

    I am willing to reinstall VC Express if I know that the program will actually work.

    I could upload those files in order to assist in any way.

    Could you do that for me?

    Maybe a screen shot of the results?

    Thanks,

    Andy

  • I am at this point in my project.

    Where is the Win32 App Wizard?

    1. In the Win32 Application Wizard , click Application Settings to reveal options for Application type. Under
      Additional Options , select Empty Project and then click
      Finish .

    2. Further on down is this.

    3. Can I go straight to making the executable?

    Can I stop the autoformatting for my replies?

    Thanks.

    1. To build and examine the program

      1. On the Build menu, click Build Solution .

        The Output window displays information about the compilation progress, for example, the location of the build log and a message that states the build status.

      2. On the Debug menu, click Start without Debugging .

        If you used the sample program, a command window is displayed and shows whether certain integers are found in the set.

  • Hello Raleigh77,

    If you compiling from command line, just add /entry:wmain

    Regards,

    Andrew

  • Thanks Andrew.

    I have used Visual C++ only about 10 times.

    I will look at the help section for command line and see what is involved.

    Andy

  • Clicked on Building on the Command Line and got:

  • Walkthrough:  Compiling a Native C++ Program on the Command Line (C++)

  • Thanks, seeing some good progress.

    Andy

    report_event.cpp
    C:Program FilesMicrosoft SDKsWindowsv6.0Aincludeprovider.h(25) : error C2470: ‘Provider’ : looks like a function definition, but there is no parameter list; skipping apparent body
    report_event.cpp(38) : error C2065: ‘UI_CATEGORY’ : undeclared identifier
    report_event.cpp(38) : error C2065: ‘MSG_INVALID_COMMAND’ : undeclared identifier
    report_event.cpp(40) : error C2065: ‘MSG_INVALID_COMMAND’ : undeclared identifier
    report_event.cpp(46) : error C2065: ‘DATABASE_CATEGORY’ : undeclared identifier
    report_event.cpp(46) : error C2065: ‘MSG_BAD_FILE_CONTENTS’ : undeclared identifier
    report_event.cpp(48) : error C2065: ‘MSG_BAD_FILE_CONTENTS’ : undeclared identifier
    report_event.cpp(55) : error C2065: ‘NETWORK_CATEGORY’ : undeclared identifier
    report_event.cpp(55) : error C2065: ‘MSG_RETRIES’ : undeclared identifier
    report_event.cpp(57) : error C2065: ‘MSG_RETRIES’ : undeclared identifier
    report_event.cpp(64) : error C2065: ‘UI_CATEGORY’ : undeclared identifier
    report_event.cpp(64) : error C2065: ‘MSG_COMPUTE_CONVERSION’ : undeclared identifier
    report_event.cpp(66) : error C2065: ‘MSG_COMPUTE_CONVERSION’ : undeclared identifier

  • C:Program FilesMicrosoft SDKsWindowsv6.0Aincludeprovider.h(25) : error C2470: ‘Provider’ : looks like a function definition, but there is no parameter list; skipping apparent body

    Are we supposed to guess what line 25 of provider.h contains?

    — Wayne

  •  // MyEventProvider.mc
     // This is the header section.
     // The following are the categories of events.
    //
    //  Values are 32 bit values layed out as follows:
    //
    //   3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
    //   1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
    //  +—+-+-+————————+——————————-+
    //  |Sev|C|R|     Facility          |               Code           
    |
    //  +—+-+-+————————+——————————-+
    //
    //  where
    //
    //      Sev — is the severity code
    //
    //          00 — Success
    //          01 — Informational
    //          10 — Warning
    //          11 — Error
    //
    //      C — is the Customer code flag
    //
    //      R — is a reserved bit
    //
    //      Facility — is the facility code
    //
    //      Code — is the facility’s status code
    //
    //
    // Define the facility codes
    //
    #define FACILITY_SYSTEM                  0x0
    #define FACILITY_STUBS                   0x3
    #define FACILITY_RUNTIME                 0x2
    #define FACILITY_IO_ERROR_CODE           0x4

    //
    // Define the severity codes
    //
    #define STATUS_SEVERITY_WARNING          0x2
    #define STATUS_SEVERITY_SUCCESS          0x0
    #define STATUS_SEVERITY_INFORMATIONAL    0x1
    #define STATUS_SEVERITY_ERROR            0x3

    //
    // MessageId: NETWORK_CATEGORY
    //
    // MessageText:
    //
    //  Network Events
    //
    #define NETWORK_CATEGORY                 ((WORD)0x00000001L)

    //
    // MessageId: DATABASE_CATEGORY
    //
    // MessageText:
    //
    //  Database Events
    //
    #define DATABASE_CATEGORY                ((WORD)0x00000002L)

    //
    // MessageId: UI_CATEGORY
    //
    // MessageText:
    //
    //  UI Events
    //
    #define UI_CATEGORY                      ((WORD)0x00000003L)

     // The following are the message definitions.
    //
    // MessageId: MSG_INVALID_COMMAND
    //
    // MessageText:
    //
    //  The command is not valid.
    //
    #define MSG_INVALID_COMMAND              ((DWORD)0xC0020100L)

    //
    // MessageId: MSG_BAD_FILE_CONTENTS
    //
    // MessageText:
    //
    //  File %1 contains content that is not valid.
    //
    #define MSG_BAD_FILE_CONTENTS            ((DWORD)0xC0000101L)

    //
    // MessageId: MSG_RETRIES
    //
    // MessageText:
    //
    //  There have been %1 retries with %2 success! Disconnect from
    //  the server and try again later.
    //
    #define MSG_RETRIES                      ((DWORD)0x80000102L)

    //
    // MessageId: MSG_COMPUTE_CONVERSION
    //
    // MessageText:
    //
    //  %1 %%4096 = %2 %%4097.
    //
    #define MSG_COMPUTE_CONVERSION           ((DWORD)0x40000103L)

     // The following are the parameter strings */
    //
    // MessageId: QUARTS_UNITS
    //
    // MessageText:
    //
    //  quarts%0
    //
    #define QUARTS_UNITS                     ((DWORD)0x00001000L)

    //
    // MessageId: GALLONS_UNITS
    //
    // MessageText:
    //
    //  gallons%0
    //
    #define GALLONS_UNITS                    ((DWORD)0x00001001L)

  • <sigh> Are we supposed to guess which line generated the error?

    — Wayne

  • If you can’t help me without criticizing me, then I can do without your «Help.»

    Andy

  • Raleigh77 wrote:

    >

    >Thanks, seeing some good progress.

    >

    >Andy

    >

    >report_event.cpp

    >C:Program FilesMicrosoft SDKsWindowsv6.0Aincludeprovider.h(25) : error C2470: ‘Provider’ : looks like a function definition, but there is no parameter list; skipping apparent body

    >report_event.cpp(38) : error C2065: ‘UI_CATEGORY’ : undeclared identifier

    Are you including <windows.h> as your first include? The word before

    «Provider» in provider.h is POLARITY, which is defined in <polarity.h>,

    which should have been included, if you did things in the proper order.

    Tim Roberts, timr@probo.com

    Providenza & Boekelheide, Inc.


    Tim Roberts, DDK MVP

  • Thanks Tim.

    There is no reference to Polarity in any of my sources.

    I am using everything at the website that was provided.

    I will have to check but I believe that windows.h is in the source code.

    I assume that VB C++ knows what to do and that it was included in the package

    that I downloaded.

    Andy

  • chocolatemint77581 wrote:

    >

    >There is no reference to Polarity in any of my sources.

    Yes, I know that. There are thousands and thousands of standard API

    include files, and those files depend greatly on one another, and on a

    particular ordering. Somehow, you have caused a standard file to be

    included without one of the files it depends on.

    That can happen if you #include a specific file by name without including

    <windows.h> first.

    >I am using everything at the website that was provided.

    >

    >I will have to check but I believe that windows.h is in the source code.

    >

    >I assume that VB C++ knows what to do and that it was included in the package

    >that I downloaded.

    There are rules to be followed to use these APIs. It’s a little dangerous

    to start compiling code without understanding what it does.

    Tim Roberts, timr@probo.com

    Providenza & Boekelheide, Inc.


    Tim Roberts, DDK MVP

  • http://msdn.microsoft.com/en-us/library/aa363677%28v=vs.85%29.aspx

    The source came from above, and as you can see, it is/was from Microsoft.

    The following example shows how to use the
    NotifyChangeEventLog function to receive notification when an event is logged.

    For the future, I will consider the possibility that any code, may be incomplete.

    But I did learn a lot from the process. 🙂

    Take care,

                     Andy

  • chocolatemint77581 wrote:

    >

    >

    >The source came from above, and as you can see, it is/was from Microsoft.

    >

    >The following example shows how to use the NotifyChangeEventLog function to receive notification when an event is logged.

    >

    >For the future, I will consider the possibility that any code, may be incomplete.

    I don’t see how you get that. I just cut-and-pasted that text into a file

    called x.cpp, then did:

    cl x.cpp

    and it compiled and linked without any further ado.

    Still, if you have achieved success, that’s what matters.

    Tim Roberts, timr@probo.com

    Providenza & Boekelheide, Inc.


    Tim Roberts, DDK MVP

  • #define PROVIDER_NAME L"MyEventProvider"
    #define RESOURCE_DLL L"<path>\Provider.dll"

    But did your .exe run correctly ?

    If it did, you will have an event at the end of a specified event log.

    ( ReportEvent function writes an entry at the end of the specified event log.)

    I have some other questions for you.

    For the program to work, it needs a path to the dll.

    Did you change <path> to the actual path?

    Did you make provider.dll ?

    And no, I did not achieve sucess.

    Take care,

                    Andy

  • Hello people,

    I have this problem in VS2010 10.0.30319.1 when i use template. if i put:

    template <typename T>

    int main(){

    return 0;

    }

    i will get this LNK1561 error…

    • Edited by
      Le10sn
      Saturday, October 13, 2012 9:52 PM

  • Le10sn wrote:

    I have this problem in VS2010 10.0.30319.1 when i use template. if i  put:

    template <typename T>

    int main(){

    return 0;

    }

    i will get this LNK1561 error…

    main() function cannot be a template. Think about it: main() is called  by the operating system — how is the OS supposed to know which type to  use for T?


    Igor Tandetnik

    • Proposed as answer by
      madhudskumar
      Friday, July 18, 2014 4:38 AM
    • Unproposed as answer by
      madhudskumar
      Friday, July 18, 2014 4:38 AM

  • Remove the void from the parameters of the main()

    it worked for me 

Я впервые установил MS VS VC++, чтобы начать программировать OpenGL с библиотекой GLFW. Я следую инструкциям о том, как установить его на http://shawndeprey.blogspot.com/2012/02/setting-up-glfw-in-visual-studio-2010.html
Затем я написал эту простую программу, чтобы протестировать ее, и она работала в Eclipse:

#include <stdlib.h>
#include <GL/glfw.h>

using namespace std;

int main()
{
    int running = GL_TRUE;
    if (!glfwInit()) {
        exit(EXIT_FAILURE);
    }

    if (!glfwOpenWindow(300, 300, 0, 0, 0, 0, 0, 0, GLFW_WINDOW)) {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    while (running) {
        // glClear( GL_COLOR_BUFFER_BIT );
        glfwSwapBuffers();
        running = !glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED);
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
    return 0;
}

Но затем я получил эту ужасную ошибку:

------ Build started: Project: first1, Configuration: Debug Win32 ------
   LINK : fatal error LNK1561: entry point must be defined
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Я знаю, я искал в Интернете, и единственное решение, которое я нашел, было «Это требует main() функция, чтобы работать». Очевидно, она у меня есть, но она все равно выдает ту же фатальную ошибку 🙁

Было бы здорово получить ответ о том, как это исправить. Может быть, у меня ошибка в процессе установки или что-то в этом роде.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка 1 error c2065 i необъявленный идентификатор
  • Ошибка 1 10087 на телефоне самсунг