Неопределенная ссылка в c ... Что я делаю не так? - PullRequest
0 голосов
/ 14 декабря 2011

У меня есть следующий код ... который выдает main.cpp:18: undefined reference to phrase_init() Исходя из C# опыта C немного раздражает, особенно при попытке выяснить, где проблема :( Любая идея или указатель будет принята с благодарностью!

phrase.h:

#ifndef PHRASE_H
#define PHRASE_H

typedef struct
{
    char* Word1;
    char* Word2;
} Phrase;

Phrase* phrase_init(void);

#endif

Phrase.c:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

#include "phrase.h"

Phrase* phrase_init()
{
    Phrase* phrase = (Phrase *)malloc(sizeof(Phrase));

    phrase->Word1 = (char *)malloc(sizeof(char));
    phrase->Word2 = (char *)malloc(sizeof(char));

    return phrase;
}

main.c

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <cctype>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

#include "phrase.h"

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

    char* word1 = "Testing";
    char* word2 = "Word2";

    Phrase* test = phrase_init();
    strcpy(test->Word1, word1);
    strcpy(test->Word2, word2);

    printf("Word 1: %s", test->Word1);
    printf("Word 2: %s", test->Word2);

    scanf("%s", word1);

}

Makefile:

#
#  There exist several targets which are by default empty and which can be 
#  used for execution of your targets. These targets are usually executed 
#  before and after some main targets. They are: 
#
#     .build-pre:              called before 'build' target
#     .build-post:             called after 'build' target
#     .clean-pre:              called before 'clean' target
#     .clean-post:             called after 'clean' target
#     .clobber-pre:            called before 'clobber' target
#     .clobber-post:           called after 'clobber' target
#     .all-pre:                called before 'all' target
#     .all-post:               called after 'all' target
#     .help-pre:               called before 'help' target
#     .help-post:              called after 'help' target
#
#  Targets beginning with '.' are not intended to be called on their own.
#
#  Main targets can be executed directly, and they are:
#  
#     build                    build a specific configuration
#     clean                    remove built files from a configuration
#     clobber                  remove all built files
#     all                      build all configurations
#     help                     print help mesage
#  
#  Targets .build-impl, .clean-impl, .clobber-impl, .all-impl, and
#  .help-impl are implemented in nbproject/makefile-impl.mk.
#
#  Available make variables:
#
#     CND_BASEDIR                base directory for relative paths
#     CND_DISTDIR                default top distribution directory (build artifacts)
#     CND_BUILDDIR               default top build directory (object files, ...)
#     CONF                       name of current configuration
#     CND_PLATFORM_${CONF}       platform name (current configuration)
#     CND_ARTIFACT_DIR_${CONF}   directory of build artifact (current configuration)
#     CND_ARTIFACT_NAME_${CONF}  name of build artifact (current configuration)
#     CND_ARTIFACT_PATH_${CONF}  path to build artifact (current configuration)
#     CND_PACKAGE_DIR_${CONF}    directory of package (current configuration)
#     CND_PACKAGE_NAME_${CONF}   name of package (current configuration)
#     CND_PACKAGE_PATH_${CONF}   path to package (current configuration)
#
# NOCDDL


# Environment 
MKDIR=mkdir
CP=cp
CCADMIN=CCadmin


# build
build: .build-post

.build-pre:
# Add your pre 'build' code here...

.build-post: .build-impl
# Add your post 'build' code here...


# clean
clean: .clean-post

.clean-pre:
# Add your pre 'clean' code here...

.clean-post: .clean-impl
# Add your post 'clean' code here...


# clobber
clobber: .clobber-post

.clobber-pre:
# Add your pre 'clobber' code here...

.clobber-post: .clobber-impl
# Add your post 'clobber' code here...


# all
all: .all-post

.all-pre:
# Add your pre 'all' code here...

.all-post: .all-impl
# Add your post 'all' code here...


# build tests
build-tests: .build-tests-post

.build-tests-pre:
# Add your pre 'build-tests' code here...

.build-tests-post: .build-tests-impl
# Add your post 'build-tests' code here...


# run tests
test: .test-post

.test-pre:
# Add your pre 'test' code here...

.test-post: .test-impl
# Add your post 'test' code here...


# help
help: .help-post

.help-pre:
# Add your pre 'help' code here...

.help-post: .help-impl
# Add your post 'help' code here...



# include project implementation makefile
include nbproject/Makefile-impl.mk

# include project make variables
include nbproject/Makefile-variables.mk

Ответы [ 2 ]

5 голосов
/ 14 декабря 2011

Вы должны указать компоновщику, где найти символ.

Например:

g++ -c phrase.cpp            # creates phrase.o which defines phrase_init()
g++ -c main.cpp              # creates main.o which refers to phrase_init()
g++ phrase.o main.o -o main  # creates executable file "main"

Или выполнить все вышеперечисленное в одной команде:

g++ phrase.cpp main.cpp -o main

Обратите внимание, что я предполагаю, что оба исходных файла являются C ++ и имеют имена с расширениями .cpp. Ваш вопрос относится к файлам с расширениями .c и .cpp, и вопрос помечен .

Если вы используете C, то вам не следует использовать специфичные для C ++ заголовки в main.c, и вы должны использовать gcc вместо g++.

Если вы используете C ++, все ваши исходные файлы должны иметь суффиксы .cpp, и вы должны использовать g++.

И если вы пытаетесь смешать C и C ++, тогда вы должны использовать extern "C", чтобы компилятор знал, что вы делаете (но обычно проще использовать чистый C ++).

1 голос
/ 14 декабря 2011

И вы действительно должны скомпилировать с -Wall -g, поэтому добавьте к вашему Makefile

CXXFLAGS+= -Wall -g
CFLAGS+= -Wall -g

первое для C ++, второе для C

Я также думаю, что вы должнынаписать от руки (проще) Makefile для сделать (вместо копирования более сложного Makefile, который вы не понимаете).

...